简体   繁体   中英

istream::ignore and getline() confusion

I am helping someone with C++ input even though I don't know C++ myself. Here's a short example:

#include <iostream>
#include <string>

using namespace std;

int main() {
    int i;
    string s;

    cout << "enter i:\n";
    cin >> i;
    cout << "enter s:\n";
    getline(cin, s);
    //cin.ignore(100, '\n');
    cout << "i: " << i << ", s: " << s << "\n";
}

As expected, the getline() call will not prompt the user for input because it will simply swallow the trailing \\n after the cin >> i call and return immediately. What I find odd is that if you uncomment the cin.ignore() call, the getline() call will prompt the user for input (even though nothing will be saved into s ). Could someone explain why? In my view, the line in question should not change the behaviour at all.

What I find odd is that if you uncomment the cin.ignore() call, the getline() call will prompt the user for input

No, it won't. It's the ignore statement that's prompting the user. As you have it, it's doing essentially the same thing as getline does, except that it will only read up to 100 characters, and it just throws them away.

Well, no. It is not the case that " getline() will prompt the user for input". Clearly the ignore statement comes after the getline() one.

What happens is that the ignore() statement simply blocks until it fulfils its task, ie gobble up 100 characters or a newline, whichever comes first (but mind the input buffering).

As a general, though not directly related, piece of advice: don't mix token extraction ( >> ) and getline() , for exactly this problem concerning newlines. Much better to just stick to one thing; preferably line reading so you can deal with errors and repeat the prompt. Also consider any unchecked read operation ( >> , getline() , or istream::read() ) a programming error; there should be conditionals surrounding all of those.

It's not the getline call that's waiting for input, it's the ignore one that is waiting for things to ignore.

Put the ignore call before the getline .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM