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

让人想犯罪 __ 提交于 2019-11-26 22:00:55

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.

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