Why doesn't std::getline block?

匿名 (未验证) 提交于 2019-12-03 08:48:34

问题:

I have this code in an Objective-C class (in an Objective-C++ file):

+(NSString *)readString {     string res;     std::getline(cin, res);     return [NSString stringWithCString:res.c_str() encoding:NSASCIIStringEncoding]; } 

When I run it, I get a zero-length string, Every time. Never given the chance to type at the command line. Nothing. When I copy this code verbatim into main(), it works. I have ARC on under Build Settings. I have no clue what it going on. OSX 10.7.4, Xcode 4.3.2.

It is a console application.

回答1:

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; 


回答2:

You can simply do:

cin.ignore(); 

or use

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

before using getline()



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