user1809300
user1809300

Reputation: 723

Weird scanf issue in C

Let's say that I use scanf to, for example, read a character from the keyboard. After that I use printf to print the character I just read.

scanf("%c",&ch);
printf("%c",ch);

When scanf is reading the character, I must press enter to continue and run the printf, right?

And let's say I enter ABCD with the keyboard. After that printf will print A.

But when I do this:

do {
   scanf("%c",&ch);
   printf("%c",ch);
} while (ch!='\n');

and enter ABCD with the keyboard, I assume that the printf must print A. And because A is not \n it will continue the loop, right?

But instead of this it will print ABCD. Why does this happen?

Upvotes: 0

Views: 644

Answers (3)

Šimon Tóth
Šimon Tóth

Reputation: 36423

in scanf i must press enter to continue and run the printf right?

Nope. As long as there is a character to be read, it will be read.

i put in scanf ABCD after that printf will print A ...

If you input ABCD and enter, the input will now contain five characters. A, B, C, D and a newline. Your cycle will read the characters A, B, C, D in sequence and then read the newline.

Upvotes: 4

kcbanner
kcbanner

Reputation: 4078

scanf does not wait for you to press enter, it simple tries to read in what you typed if it matched your format string. If you had used %s, then it would wait until a whitespace character before matching.

This thread may also be useful: why does scanf not wait for user input after it fails one time?

Upvotes: 1

Daniel Fischer
Daniel Fischer

Reputation: 183873

When you type in "ABCD\n", each scanf("%c",&ch); reads one char from the input buffer, until the newline is reached.

So after the 'A' is printed, there is still a "BCD\n" in the buffer, so that the next scanf immediately succeeds reading another char, 'B' in the next iteration of the loop.

Upvotes: 7

Related Questions