2014-10-11 96 views
3

我试过四处寻找,我似乎无法找到错误所在。我知道它必须与我用fgets的方式有关,但我无法弄清楚我的生活是什么。我读过混合fgets和scanf可能会产生错误,所以我甚至改变了我的第二个scanf到fgets,它仍然跳过我的其余输入,只打印第一个。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++; 
    } 
} 

我的投入是乔,是的,比尔,是的,约翰,没有。如果我利用scanf代替第一个fgets,所有都按照计划进行,但我希望能够使用包含空格的全名。我哪里错了?

回答

5

当程序显示Do you have more students to input?并且您输入yes,然后在控制台上按回车,则\n将被存储在输入流中。

您需要从输入流中删除\n。要做到这一点,只需拨打getchar()函数即可。

如果不混合使用scanffgets将会很好。 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 main 
+0

辉煌!谢谢! – user3591385 2014-10-11 20:31:28

+2

我宁愿看到:'int c; while((c = getchar())!= EOF && c!='\ n');'循环体的分号在它自己的一行上。这可以保护你,如果用户输入'yes please'或者只是在输入末尾放置一个空格。在这种情况下,使用'int c'而不是'char c'至关重要。在原始代码中,你不使用'c'(所以我的默认编译器选项会抱怨一个设置但未使用的变量;如果我在这里使用了代码,我最终会得到'(void)getchar()')所以无法区分'EOF'和有效字符。 – 2014-10-11 22:41:49

+0

@JonathanLeffler:我很高兴你对我的帖子提出了改进建议。谢谢:)按照您的建议进行更改。如果用户输入'yes',更新后的更改也会生效。 – user1336087 2014-10-12 08:59:24