C++ iostream: Using cin >> var and getline(cin, var) input errors

旧街凉风 提交于 2019-12-01 11:00:35

cin>>var;

only grabs the var from the buffer, it leaves the \n in the buffer, which is then immediately grabbed up by the getline

So, following is just fine, (if I understood correctly your problem)

cin>>var;
cin.ignore();     //Skip trailing '\n'
getline(cin, var);

As per your edited post

You don't have to use cin.ignore(); for geline

This extracts characters from buffer and stores them into firstName or (lastName) until the delimitation character here -newline ('\n').

ignore() does not skip a line, it skips a character. Could you send example code and elaborate on the need for cin.ignore()?

std::cin.ignore() will ignore the first character of your input.

For your case, use std::cin.ignore() after std::cin and then getline() to ignore newline character as:

cin>>ch;
cin.ignore();  //to skip the newline character in the buffer
getline(cin,var);

You are using std::isstream::ignore() before std::getline(). std::cin.ignore() will extract the first character from the input sequence and discard that.

http://www.cplusplus.com/reference/istream/istream/ignore/

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