开发者

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

This question already has answers here: Closed 11 years ago.

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 , fatherNam开发者_StackOverflow中文版e );

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 :

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

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.


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 >>


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 );


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜