Google Groups no longer supports new Usenet posts or subscriptions. Historical content remains viewable.
Dismiss

if (cin >> day) day; else break;

40 views
Skip to first unread message

mathewji

unread,
Dec 28, 2014, 2:29:33 PM12/28/14
to
With:

int day = 0;
while(true) {
cout << "number: ";
cin >> day }

Inputting anything besides an int into day, causes nonstop output of "number: ". I found a solution as:

int day = 0;
while(true) {
cout << "number: ";
if (cin >> day) day;
else break; }

Anyone know why this happens?

Marcel Mueller

unread,
Dec 28, 2014, 2:43:48 PM12/28/14
to
On 28.12.14 20.29, mathewji wrote:
> With:
>
> int day = 0;
> while(true) {
> cout << "number: ";
> cin >> day }
>
> Inputting anything besides an int into day, causes nonstop output of "number: ". I found a solution as:

If no int can be read from cin then the >> operator does nothing but
setting an error flag which you did not check.

> int day = 0;
> while(true) {
> cout << "number: ";
> if (cin >> day) day;
> else break; }
>
> Anyone know why this happens?

Now you checked for the error by implicitly converting cin (istream) to
bool.


Marcel

Barry Schwarz

unread,
Dec 28, 2014, 8:05:50 PM12/28/14
to
When cin encounters a character that cannot be part of the int, it
terminates and leaves that character in the buffer. The next time cin
tries to extract an int, it runs into the same "invalid" character.
Repeat until bored.

--
Remove del for email
Message has been deleted
Message has been deleted
0 new messages