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.
Well, no. It is not the case that “
getline()will prompt the user for input”. Clearly theignorestatement comes after thegetline()one.What happens is that the
ignore()statement simply blocks until it fulfils its task, i.e. 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 (
>>) andgetline(), 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(), oristream::read()) a programming error; there should be conditionals surrounding all of those.