Wednesday, January 10, 2007

iostream trap


Look at this program

#include <iostream>
#include <string>
using namespace std;

int main() {
    cout << "intput 1" << endl;
    int i;
    cin >> i;

    cout << "input 2" << endl;
    string foo;
    getline(cin, foo);
    return 0;
}

A sample run of this program is:


input 1
1
input 2

It feels like the getline command is not executed. If you print the foo string afterwards it is empty. What is going on?
The reason for this is that cin >> i reads an integer from the input stream. This integer is delimited by the newline which gets into the input stream as the user hits return - and stays there. The subsequent getline then reads from the input stream until the first newline which in this case is the one before. So getline does nothing but consuming the newline.

One can fix this situation by calling getline twice. A better possibility is to tell the istream library to discard everything until the next newline. This can be done like this:

cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n')

I will not start to bash C++ iostreams now. I think just the facts is enough here. Thanks to Roker and netlest on #c++

No comments:

Post a Comment