2014-10-11 72 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