问题
void main()
{
int cnt=1;
char i;
while(cnt<4)
{
printf("\nenter the character");
scanf("%c",&i);
if(i>64 && i<91)
printf("\ncharacter is entered");
else
printf("\nnumber is entered");
cnt++;
}
}
In the above program, during the second iteration, i
automatically takes 10. So the control goes to else
part. Can anyone help me find what is the issue?
回答1:
In the first iteration, you type a character and press Enter. scanf
consumes the character you entered, leaving the \n
in the standard input stream (stdin
).
In the second iteration, scanf
sees the \n
character consumes it, thus not waiting for further input.
You can tell scanf
to read and discard the next character by using:
scanf("%c%*c", &i);
or you can tell scanf
to read and discard all whitespace characters, if any, before reading a character and storing it in i
by using:
scanf(" %c",&i);
/* ↑ Note the space */
来源:https://stackoverflow.com/questions/35110942/scanfc-automatically-reads-10