Grego
Grego

Reputation: 2250

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,"");

     printf("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.

Upvotes: 0

Views: 3129

Answers (4)

hlatsiieycreates
hlatsiieycreates

Reputation: 1

I hope I answer your question.

What I found to work is to add this line in the loop.

fflush(stdin);

more especially after

scanf("%d", &age_temp);

Upvotes: 0

K. P. MacGregor
K. P. MacGregor

Reputation: 206

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.

Upvotes: 4

Mihran Hovsepyan
Mihran Hovsepyan

Reputation: 11088

You should open stdin in binary mode. Use freopen(NULL, "rb", stdin) to do this.

See C read binary stdin for more details.

Upvotes: -1

BenjaminB
BenjaminB

Reputation: 1849

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.

Upvotes: 2

Related Questions