Why not std :: getline block?

I have this code in the Objective-C class (in the 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 string of zero length, every time. They were never given the ability to type on the command line. Nothing. When I copy this code verbatim into main() , it works. I have ARC in Build settings. I have no idea what is going on. OSX 10.7.4, Xcode 4.3.2.

This is a console application.

+5
source share
2 answers

This means that input awaiting read is pending. You can clear the input:

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

If this happens, it means that you did not read all the data from the input stream in the previous reading. The above code will destroy any user input before reading more.

This probably means that you are mixing operator>> with std::getline() to read user input. You should probably select one method and use it (std :: getline ()) throughout the application (you can mix them, you just need to be more careful and remove the "\ n" after using the → operator to make sure that the subsequent std :: getline () are not confused ..

If you want to read a number by reading a line, analyze the line number:

 std::getline(cin, line); std::stringstream linestream(line); linestream >> value; 
+9
source

You can simply do:

 cin.ignore(); 

or use

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

before using getline()

+2
source

Source: https://habr.com/ru/post/922532/


All Articles