getline(cin.name) gets skipped

匿名 (未验证) 提交于 2019-12-03 08:52:47

问题:

I call a function from a function in C++ that has the line getline(cin,name) where name is a string. the first time through the loop, the program does not wait for input. It will on all other passes through the loop. Any ideas on why?

void getName (string& name) {       int nameLen;        do{           cout << "Enter the last Name of the resident." << endl << endl               << "There should not be any spaces and no more than 15"               << " characters in the name."  << endl;             getline(cin,name);             cout << endl;             nameLen = name.length();// set len to number of characters input           cout << "last" << name << endl;          }       while (nameLen < LastNameLength);          return; } 

回答1:

Make sure there isn't left overs since the last time you read something from cin, like:
In an earlier point in your program:

int number; cin >> number; 

The input you give:

5 

Later in the program:

getline(cin,name); 

and getline will seem to not be called, but rather it collected the newline from the last time you took input because when you use cin >> it leaves new lines.



回答2:

It may be because of the input stream. The getline function stops reading input after is receives the first newline char. If for example there are multiple newlines within the buffer of std::cin - the getline will return every time it encounters one.

Check the input you are expecting.



回答3:

Do you have any: cin << variableName;

lines of code? I ran into getline() skipping run-time errors when I was using:

cin << intvariable and subsequently getline(cin, variable).

This is because the cin stream object holds a buffer of input. When you enter the newline character I assume it is trunacated from the stream going to the variable asisgnment, yet is still contained within the cin object instance itself.

One workaround I used is cin.ignore(); after the cin << integer statement.

Another user mentioned parsing all input from getline into integers, floats - not root beer -, and strings. Good luck and check your code for the dual use of cin & getline().



标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!