ttoshiro
ttoshiro

Reputation: 526

Why is the first digit of a string still read and output in a while loop where the condition !isdigit is false?

Note: I know the solution that would solve the issue, but I don't understand the "computer logic," or what is going on behind the compiler.

In my C++ textbook, there is a blurb of example code that reads:

cout << "Enter a line of input:\n";
char next;
while ((!isdigit (next)) && (next != '\n'))
{
  cin.get (next);
  cout << next;
}
cout << "<END OF OUTPUT>";

... Paired with the example input: I'll see you at 10:30 AM.

I would expect, after typing in the input, for the output to be I'll see you at <END OF OUTPUT>. Instead, the first digit, "1," is also output, such that it becomes I'll see you at 1<END OF OUTPUT>. Why is this? Is this because the statement cin.get (next); is not declared/initialized outside of the while loop, and thus the first next value tested in the while loop's conditional parameters is not actually the first character of the keyboard input? Or does the while loop run an extra iteration when the next condition is not satisfied?

If it's the former, what does the computer test if next is not set to a value? And why does the first digit ("1") read still meet the condition to run the loop again one more time before terminating?

Upvotes: 0

Views: 58

Answers (1)

StefanKssmr
StefanKssmr

Reputation: 1226

As mentioned in the comments, you have to initialize next before using it, otherwise it is undefined behavior.

Now lets assume, next is properly initialized to a non-digit character. The condition (!isdigit (next)) && (next != '\n') is checked once when you enter the while loop and every time when you reach the end of the statement in curly braces. In your first version, you get a new char and immediately stream it to cout. The check is done afterwards and the loop terminates as expected.

Upvotes: 1

Related Questions