Reputation: 6211
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.
Upvotes: 0
Views: 1323
Reputation: 206859
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
.
Upvotes: 1
Reputation: 477514
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, 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 (>>
) 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.
Upvotes: 1
Reputation: 103751
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.
Upvotes: 1