My code is as follows
typedef struct
{
char name[15];
char country[10];
}place_t;
int main()
{
int d;
char c;
place_t place;
printf("\nEnter the place name : ");
scanf("%s",place.name);
printf("\nEnter the coutry name : ");
scanf("%s",place.country);
printf("\nEnter the type of the place : Metropolitan/Tourist (M/T)?");
scanf("%c",&c);
printf("You entered %c",c);
return 0;
}
If I run the program, it prompts for place name and country name, but never waits for the character input from user.
I tried
fflush(stdin);
fflush(stdout);
Neither work.
Note : Instead of a character, if I write a similar code to get an integer or a float, it prompts for values and the code works just fine.
int d;
printf("\nEnter the type of the place : Metropolitan/Tourist (M/T)?");
scanf("%d",&d);
Why does this happen? Is there anything wrong in the code?
The problem is that
scanfleaves the whitespace following entered non-whitespace characters in the stream buffer, which is what thescanf(%c...)then reads. But wait a second…In addition to being tricky to get right, such code using
scanfis horribly unsafe. You’re much better off usingfgetsand parsing the string later:fgetsalways gets a full line from the input, including the newline (assuming the buffer is large enough) and you thus avoid the problem you’re having withscanf.