getline not working properly ? What could be the reasons? [duplicate]

陌路散爱 提交于 2019-11-26 08:09:01

问题


Possible Duplicate:
getline not asking for input?

There is some unique thing happening in my program. Here are some set of commands :

 cout << \"Enter the full name of student: \";  // cin name
 getline( cin , fullName );

 cout << \"\\nAge: \";  // cin age
 int age;
 cin >> age ;

cout << \"\\nFather\'s Name: \";  // cin father name
getline( cin , fatherName );

cout << \"\\nPermanent Address: \";  // cin permanent address
getline( cin , permanentAddress );

When i try to run this snippet along with the whole code.The output program works like :

\"enter

output:

Enter the full name of student:
Age: 20

Father\'s Name:
Permanent Address: xyz

If you notice ,the program didn\'t ask me the full name and went on directly to ask me the age.Then it skips the father\'s name also and asks the permanent address. What could be the reason for this ?

It is difficult for me to post the whole code because it is too large.


回答1:


Since you have not posted any code. I am going to take a guess.

A common problem while using getline with cin is getline does not ignore leading whitespace characters.

If getline is used after cin >>, the getline() sees this newline character as leading whitespace, and it just stops reading any further.

How to resolve it?

Call cin.ignore() before calling getline()

Or

make a dummy call getline() to consume the trailing newline character from the cin >>




回答2:


The problem is that you are mixing getline with cin >> input.

When you do cin >> age;, that gets the age from the input stream, but it leaves whitespace on the stream. Specifically, it will leave a newline on the input stream, which then gets read by the next getline call as an empty line.

The solution is to only use getline for getting input, and then parsing the line for the information you need.

Or to fix your code, you could do the following eg. (you'll still have to add error checking code yourself) :

cout << "Enter the full name of student: ";  // cin name
getline( cin , fullName );

cout << "\nAge: ";  // cin age
int age;
{
    std::string line;
    getline(cin, line);
    std::istringstream ss(line);
    ss >> age;
}

cout << "\nFather's Name: ";  // cin father name
getline( cin , fatherName );

cout << "\nPermanent Address: ";  // cin permanent address
getline( cin , permanentAddress );



回答3:


after the line cin >> age ; there is still the newline character \n (because you pressed enter to input the value) in the input buffer, to fix this you add a line with cin.ignore(); after reading the int.



来源:https://stackoverflow.com/questions/6649852/getline-not-working-properly-what-could-be-the-reasons

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