Problem with scanf [duplicate]
Possible Duplicate:
Simple C scanf does not work?
Why does scanf("%c", &letter);
not working. the rest is working
#inc开发者_运维技巧lude <stdio.h>
main(){
int number;
float number1;
char letter;
char letter2 [5];
printf("Enter an int: ");
scanf("%d", &number);
printf("Enter a float: ");
scanf("%f", &number1);
printf("Enter a letter: ");
scanf("%c", &letter);
printf("Enter a string: ");
scanf("%s", letter2);
printf("INT = %d\n", number);
printf("FLOAT = %f\n", number1);
printf("LETTER = %c\n", letter);
printf("LETTER2= %s\n", letter2);
getch();
}
This is because the newline (return key) after feeding float is counted as a character.
This is not a bug but it is due to fact that "\n" is considered a character in C and if you have to ignore it, you need to do that manually.
The simplest solution for your case is to eat up the newline as follows:
scanf("%f", &number1);
getchar();
This Link will help.
scanf
reads the whitespace that is left in the buffer from the previous line. To skip the whitespace, add a space to the scanf:
scanf(" %c", &letter);
The space means "skip whitespace" and the the %c means "read the following character.
精彩评论