Tried you code out in GCC 4.1.2, no problems, same output for both cases, no infinite loops!!
I had directly copy pasted your code.
stephen84s
Nearly a Posting Virtuoso
1,443 posts since Jul 2007
Reputation Points: 668
Solved Threads: 154
strange .......... i use mingw
did you entered chars not ints ??
I think that was an important information u left out ;)
Yep, it does go into the infinite loop, but so does the first one.
But why exactly its occurring I cant figure it out, I hope some of the other guys know of it.
stephen84s
Nearly a Posting Virtuoso
1,443 posts since Jul 2007
Reputation Points: 668
Solved Threads: 154
if (cin.good())
{
break;
cin.sync();
}
The sync call will never be reached in this snippet because break leaves the loop immediately.
>why ??
Because when you type a value that cin doesn't expect (ie. a non-integer character when an integer is expected), cin goes into an error state. When cin is in an error state, all input requests do nothing until you clear the state.
What your first example does (in theory) is clear the state and then discard all of the characters in the stream so that you wipe the slate clean and can try again. The second example tries to discard all of the characters in the stream first, even though the stream is still in an error state and the sync call is effectively a no-op because of it.
I say "in theory" because cin.sync() isn't required to flush the input stream.
Narue
Bad Cop
15,460 posts since Sep 2004
Reputation Points: 6,464
Solved Threads: 1,401
Narue
Bad Cop
15,460 posts since Sep 2004
Reputation Points: 6,464
Solved Threads: 1,401
>what i know that cin.rdbuf returns all what in the buffer
Kind of. It returns a pointer to the buffer object.
>but why loop happens
It's library magic. The << operator reads everything it can from the object it's given, and the buffer object will return characters from the attached stream until end-of-file. Together this "creates a loop", if that's how you want to describe it.
Narue
Bad Cop
15,460 posts since Sep 2004
Reputation Points: 6,464
Solved Threads: 1,401