Search code examples
c++objective-cmacosobjective-c++getline

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.


Solution

  • 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;