When you use scanf
and %c
, it reads any character -- including the newline character you get when you press the ENTER key.
So if you run the program and type
a <Return>
you take two trips through the loop: one to read the 'a'
and one to read the '\n'
. If you type
<Space> <Space> a <Return>
it makes four trips through the loop. And if you type
x <Return>
it only makes one trip through the loop, because it notices you typed the 'x'
, and exits.
Things will become a little more clear if you print out each character you receive:
for (int i = 0; a != 'x'; )
{
printf("Enter 'a' : ");
scanf("%c",&a);
printf("you typed %d = %c\n", a, a);
}
When you see it printing
you typed 10 =
that's one of the newlines. (The value of '\n'
is 10 in ASCII.)
I said that %c
reads any character -- but that's somewhat unusual. Most of scanf
's other format specifiers -- %d
, %f
, %s
, etc. -- skip over "whitespace" -- that is, spaces, tabs, newlines, and a few others. But %c
does not skip over those, because its job is to read exactly one character, and someone thought you might want to use it to read whitespace characters, too.