\n

this code works only if there is \n before %c in scanf statement. please explain me why?

1
2
3
4
5
6
7
8
9
10
11
12
13
#include<stdio.h>
#include<conio.h>

int main()
{
char ch;
do{
printf("k");
printf("do u want to stop?(y/n)");
scanf("\n%c",&ch);
}while(ch=='n');
getch();
}
When you enter n on keyboard, you hit two keys: n and Enter. Two characters are sent to the program: 'n' and '\n'

On the first loop iteration, scanf processed 'n', but not '\n' (there are no more directives after %c, so once it reads a char, it's done)

On the second loop iteration, scanf('%c',&ch); processed '\n' without waiting for more input, and proceeded to check if ch == 'n', which it wasn't. So the loop ended.

To consume all endlines, spaces, and tabs, and make sure the char you read is a non-whitespace char, you can use scanf("\n%c",&ch);, although scanf(" %c",&ch); (with a space before %c) is a more idiomatic.
Last edited on
Then there is specification %c then white spaces are not skipped. So when you enter a symbol and after that you press ENTER the input buffer will contain two characters: the symbol and the new line character. Next time when you read a a symbol again if there is no \n in the format string then ch will get this new line symbol instead of the character you was going to read.
Last edited on
Topic archived. No new replies allowed.