2016-11-28 51 views
0

我必須編寫一個程序,讀取學生姓名和ID列表,並根據名字,姓氏和ID對它們進行排序。但目前我的代碼有兩個問題。在列表中閱讀

#include <stdio.h> 

int main() { 
    char firstName[200][21], lastName[200][51]; 
    unsigned short id[200]; // used short to decrease memory usage 
    int i; 

    for (i=0; i<200; ++i) { 
    printf("Enter first name of student %d: ",i+1); 
    getchar(); // FIX to consume enter 
    fgets(firstName[i],21,stdin); 
    printf("Enter last name of student %d: ",i+1); 
    fgets(firstName[i],21,stdin); 
    printf("Enter student number of student %d: ",i+1); 
    scanf("%hu",&id[i]); 
    printf("You've entered %s %s with ID %hu",firstName[i],lastName[i],id[i]); 
    } 

// other functions to do after reading in the data is successfully done 
} 
  1. 閱讀中的值必須,如果在校生達到200或者如果用戶輸入EOF停止。
  2. 學生的名字或姓氏可能由多個部分組成(類似於「約翰約翰」,所以我用fgets代替了scanf和%s來讀取空格後的單詞,但它失敗了,只有姓氏是。?存儲

你能告訴我如何停止與EOF循環和讀出第一和最後一個名稱正確由於

+0

你檢查你的['getchar'(http://en.cppreference.com/返回的值w/c/io/getchar),['fgets'](http://en.cppreference.com/w/c/io/fgets)和['scanf'](http://en.cppreference.com/ w/c/io/fscanf)來電? –

+0

在不相關的說明中,您應該閱讀並學習*結構*。 –

回答

3

用於檢查EOF,你可以使用函數:

feof(FILE*) // if it returns 1 then it is EOF reached. 

你可以像貝爾一樣使用它流片段:

if (feof(fp) == 1) 
break; 

和第二個問題:

printf("Enter last name of student %d: ",i+1); 
    fgets(firstName[i],21,stdin); // this is incorrect. 

使用 '姓氏' 而不是 '名字'。它應該是這樣的:

fgets(lastName[i],21,stdin); 
以這種方式要覆蓋名字的價值

+0

哦,權利thnaks我沒有看到它! –

+0

樂意幫助夥計! –

+0

它仍然讀入。我怎麼能刪除它們? –