Reputation: 1615
i have been debugging the whole night, it is very confusing that the console always jump to ask me the second runner's name, but dont give me the change to input the first runner's name.
here is segment in my main.c
Trunner runners[10];
Trunner best;
int n,i;
const char* name = "give the name for runner ";
const char* time = "give the time for runner ";
printf("How many names you have?");
scanf("%d",&n);
for(i=0;i<n;i++){
readTime(&runners[i],time);
}
for(i=0;i<n;i++){
readName(&runners[i],name);
}
here is my runner.c
void readName(Trunner *runner, const char *prompt){
printf(prompt);
fgets (runner->name,30,stdin);
//getchar();
}
and what i got, the name of runner should be in the same line as the comma, and as you can see, the first runner's name is empty.
How many names you have?3
give the time for runner 11:13
give the time for runner 14:14
give the time for runner 12:13
give the name for runner give the name for runner lily
give the name for runner lucy
the winner is:
, 11:13
, 11:13 0:0
lily
, 14:14 3:1
lucy
, 12:13 1:0
Press any key to continue . . .
Upvotes: 0
Views: 110
Reputation: 141
You used both scanf and fgets. Those 2 functions work a tad differently. Personally I dont touch scanf because of the garbage it leave in the buffer as you have seen for yourself.
\n (or newline character) remains after almost every input but the difference is that if it is left and you do scanf("%d",&someVar)
it mostly won't skip because /n isn't castable to %d BUT if there is \n in the buffer and you do scanf("&c",&someVar)
or scanf("%s",someArray)
then because \n is a character, it pulls it from the buffer as though you just pressed it.
Note that you can get rid of the buffered \n character by getchar() for example but only if you know that it is there or your program will hold waiting for a key press. Don't use fflush ever ever ever if you want you program to remain stable. Explanation http://www.gidnetwork.com/b-57.html.
You didnt post your readTime function so I can't give you the exact solution, but I can advise for every input to use fgets and then to transform to an integer you can use i=strtol(buffer,NULL,10)
for example (located in <stdlib.h>
). I suggest reading about the strtol,strtod,strtok functions as they are all you'll need for any kind of input with fgets.
Upvotes: 0
Reputation: 71009
After the scanf
's execution there is a newline character that is left. First fgets reads it and so the string remains empty. There are several options how to avoid that, but easiest one is to simply perform one fgets after the scanf, reading to a buffer the newline character.
Another(and probably better) option is to call fflush(stdin);
after the scanf
. If reading from the console(as seems to be the case) this will do the trick as it flushes the input buffer.
Upvotes: 1