[英]error in reading input using istringstream in C++
我必須接受如下輸入
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();
}
}
在上面運行代碼時,我低於 output
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
我的代碼中沒有出現錯誤是什么導致我的初始值 line 打印為 0 而不是正確的值在我的情況下它是 10 例如
請幫助
std::getline
已經讀取並忽略換行符。 所以你在“錯誤”的地方有std::ignore
。
您只想丟棄std::cin
輸入中留下的換行符。 所以刪除input()
成員 function 中的ignore
調用,而是在cin
調用之后添加它:
int n; // number of students
cin >> n;
cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
(您需要<limits>
header。)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.