Fgets Ignored after its run one time in C Programming?
So this is the code, its pretty simple, but why isn't the fgets
prompted again after the first loop? and age is. (And weirdly it works with scanf("%s",&name_temp)
but I need to grab other characters too like áéíóúÇ, spaces, so it would be better with fgets
)
int menu_option = 0;
char name_temp[80] = "";
int age_temp = 0;
while(menu_option != 9){
//strcpy(name_temp,"");
prin开发者_StackOverflow中文版tf("Type your name\n");
fgets(name_temp, 80, stdin);
printf("\nType your age\n");
scanf("%d", &age_temp);
}
(moved from the deleted answer)
Guys thanks for your answers, but I don't think you guys understood my question, test this code that I sent, and you will see that instead of appearing the thing in the Terminal for you to type, it is just ignored after the first while loop.
What I wanted is that after the first loop (while) it came back and asked again the name of the person and the person using the program would have to type again. but instead of that, after the first time of the loop, it just doesn't ask for you to type anything, the fgets is completely ignored.
please try the code and say what can I do.
I tried the freopen thing and did not work.
When I ran it, it did indeed print out "Type your name" each time through the loop, but did not wait for input, because it was getting the '\n' which the call to scanf left on the input stream. This is a common problem; one solution is to insert getchar(); at the bottom of the loop, to eat that newline.
fgets
read a line, that is, it read stdin
until \n
character is reached.
scanf
left the \n
character into stdin
.
Then, fgets
read an empty line.
You should open stdin
in binary mode. Use freopen(NULL, "rb", stdin)
to do this.
See C read binary stdin for more details.
精彩评论