Question

Could seem an old question, but the problem here isn't the use of TWO cin.get(), but of more than two! if I write (in DEV C++)
I get just one input request (s) and then end program. Now, I expected having at least two request of cin, because I expected:

char s[50];
char t[100];

char r[100];

char f[100];

cin.get(s,49);    
cin.get(t,99);
cin.get(r,99);
cin.get(f,99);

I expeted at least 2 input request, because:

first cin: buffer empty,I insert the string s and \n
second cin: I have in buffer \n still, then t=\n without input request
third cin: buffer empty, I insert the string r and \n
fourth cin: I have in buffer \n still, then f=\n without input request

But I have just the input request for s string! why have I just one input request?the buffer didn't clean with second cin.get, letting third cin.get work properly? Thanks

Was it helpful?

Solution

t does NOT equal '\n'. It's empty. .get(char*,int) will never remove the '\n' from the buffer.

Worse, the attempt to read to t will set cin to a fail state since nothing could be read, which will cause all subsequent reads of any sort from cin to fail immediately without even trying until you .clear() the fail state.

This is surprising behavior, but you seem to have already guessed at most of it as per your last sentence in the question, so, Good Job! You're learning!

http://en.cppreference.com/w/cpp/io/basic_istream/get

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top