我试着四处看看,但似乎找不到错误所在。我知道这一定与我使用fgets的方式有关,但我无论如何也搞不清楚它是什么。我读到混用fgets和scanf会产生错误,因此我甚至将第二个scanf更改为fgets,但它仍然跳过其余的输入,只打印第一个。
int addstudents = 1;
char name[20];
char morestudents[4];
for (students = 0; students<addstudents; students++)
{
printf("Please input student name\n");
fgets(name, 20, stdin);
printf("%s\n", name);
printf("Do you have more students to input?\n");
scanf("%s", morestudents);
if (strcmp(morestudents, "yes")==0)
{
addstudents++;
}
}我的输入是Joe,是,Bill,是,John,不是。如果我使用scanf代替第一个fgets,一切都按计划进行,但我希望能够使用包含空格的全名。我哪里错了?
发布于 2014-10-12 03:15:57
当程序显示Do you have more students to input?并输入yes,然后在控制台上按enter时,\n将存储在输入流中。
您需要从输入流中删除\n。为此,只需调用getchar()函数。
如果你不把scanf和fgets混在一起就好了。scanf有很多问题,最好使用fgets。
Why does everyone say not to use scanf? What should I use instead?
试一下这个例子:
#include <stdio.h>
#include <string.h>
int main (void)
{
int addstudents = 1;
char name[20];
char morestudents[4];
int students, c;
char *p;
for (students = 0; students<addstudents; students++)
{
printf("Please input student name\n");
fgets(name, 20, stdin);
//Remove `\n` from the name.
if ((p=strchr(name, '\n')) != NULL)
*p = '\0';
printf("%s\n", name);
printf("Do you have more students to input?\n");
scanf(" %s", morestudents);
if (strcmp(morestudents, "yes")==0)
{
addstudents++;
}
//Remove the \n from input stream
while ( (c = getchar()) != '\n' && c != EOF );
}
return 0;
}//end mainhttps://stackoverflow.com/questions/26318275
复制相似问题