c++ - why does scanf not work when access a input of char type in C -
this question has answer here:
- scanf() leaves new line char in buffer? 3 answers
#include <stdio.h> int main() { int age; char sex; printf("enter age: " ); scanf("%d", &age); printf("enter sex (f,m): " ); scanf("%c", &sex); printf("output message %d %c",age,sex); return 0; }
for debugging, scanf("%c", &sex); line not work properly, when input age , press enter key,it skip input part of sex , showed output message directly. however, when appended getchar(),it works properly.
#include <stdio.h> int main() { int age; char sex; printf("enter age: " ); scanf("%d", &age); printf("enter sex (f,m): " ); scanf("%c", &sex); getchar(); printf("output message %d %c",age,sex); return 0; }
what's wrong that? in general, user's input should assigned character sex while calling scanf()..
the problem here thatscanf("%c", &var)
takes whatever there in input steam (stdin
). workaround leaving space before %c
specifier.
Comments
Post a Comment