我调试了一晚上,控制台总是跳来问我第二个运行者的名字,却不给我输入第一个运行者的名字,这很困惑。
这是我的 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);
}
这是我的 runner.c
void readName(Trunner *runner, const char *prompt){
printf(prompt);
fgets (runner->name,30,stdin);
//getchar();
}
我得到的是,运行者的名字应该与逗号在同一行,正如你所看到的,第一个运行者的名字是空的。
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 . . .
最佳答案
执行scanf
后,会留下一个换行符。首先 fgets 读取它,因此字符串保持为空。有多种选择可以避免这种情况,但最简单的一种是在 scanf 之后简单地执行一次 fget,将换行符读取到缓冲区。
另一个(可能更好)选项是在 scanf
之后调用 fflush(stdin);
。如果从控制台读取(似乎是这种情况),这将在刷新输入缓冲区时发挥作用。
关于c - 为什么这个数组中的第一个元素不存储任何值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14571317/