Why doesn't std::getline block?

纵然是瞬间 提交于 2019-12-05 08:33:16

It means there is input waiting to be read on the input. You can empty the input:

cin.ignore(std::numeric_limits<std::streamsize>::max();
std::getline(cin, res);

If this is happening it means you did not read all the data off the input stream in a previous read. The above code will trash any user input before trying to read more.

This probably means that you are mixing operator>> with std::getline() for reading user input. You should probably pick one technique and use that (std::getline()) throughout your application ( you can mix them you just have to be more careful and remove the '\n' after using operator>> to make sure any subsequent std::getline() is not confused..

If you want to read a number read the line then parse the number out of the line:

std::getline(cin, line);
std::stringstream  linestream(line);

linestream >> value;

You can simply do:

cin.ignore();

or use

cin.clear();
cin.sync();

before using getline()

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