在C ++中使用istringstream读取输入时出现错误

问题描述 投票:0回答:1

我必须输入以下内容

3
10 20 30 40 50
60 70 80 90 10
20 30 40 50 60

所以我有下面的代码

class Student {

public:
    void input() {
        cin.ignore();
        string line;
        std::getline(std::cin, line);

        // build an istringstream with above received line as data source.
        std::istringstream iss{ line };
        // define vector Marks use range constructor and steam iterator
        unsigned int mark = 0;
        while (iss >> mark) {
            cout << "pushing mark " << mark << endl;
            m_vecMarks.push_back(mark);
        }
    }
private:
    vector< unsigned int > m_vecMarks;

};



int main() {
    int n; // number of students
    cin >> n;
    Student* s = new Student[n]; // an array of n students

    for (int i = 0; i < n; i++) {
        cout << "Enter the input for " << i << endl;
        s[i].input();
    }
}

虽然运行上面的代码,但我得到的是输出以下的东西

pushing mark 0
pushing mark 20
pushing mark 30
pushing mark 40
pushing mark 50
pushing mark 0
pushing mark 70
pushing mark 80
pushing mark 90
pushing mark 10
pushing mark 0
pushing mark 30
pushing mark 40
pushing mark 50
pushing mark 60

我的代码中没有错误,导致行的初始值打印为0而不是例如10的正确值

请帮助

c++
1个回答
2
投票

std::getline已读取并忽略换行符。因此,您将std::getline放在“错误”的位置。

您只想舍弃std::ignore输入中剩余的换行符。因此,请删除std::ignore成员函数中的std::cin调用,然后在std::cin调用之后立即添加它:

ignore

(您需要input()标头。]

© www.soinside.com 2019 - 2024. All rights reserved.