c++ - why does scanf not work when access a input of char type in C -


this question has answer here:

#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 %cspecifier.


Comments

Popular posts from this blog

angular - Ionic slides - dynamically add slides before and after -

minify - Minimizing css files -

Add a dynamic header in angular 2 http provider -