Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why doesn't std::getline block?

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.

like image 590
Linuxios Avatar asked Jul 06 '12 02:07

Linuxios


People also ask

Why CIN Getline is not working in C++?

The getline() function in C++ is used to read a string or a line from the input stream. The getline() function does not ignore leading white space characters. So special care should be taken care of about using getline() after cin because cin ignores white space characters and leaves it in the stream as garbage.

Does Getline stop at whitespace?

The getline function reads in an entire line including all leading and trailing whitespace up to the point where return is entered by the user.

Why does C++ Getline skip?

When execution reaches getline(cin, rp. command) the program just print "Enter repo command: " and skips the getline(cin, rp. command) line so that the user is not given time to respond.

What can I use instead of Getline in C++?

ignore() before getline() , but it either requires me to press enter before giving an input, or skips the first character of the first input. However, if I add cin. ignore() after the end of every cin >> value; block, it works.


1 Answers

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;
like image 116
Martin York Avatar answered Sep 28 '22 15:09

Martin York