2014-10-29 258 views
0

嗨我有一個未知問題getline()。我的程序應該提示提示,然後getline()應該在用戶輸入中讀取,但由於某種原因,每次運行時都會提示並跳到下一個提示,而不允許我輸入任何內容。我會發布代碼,希望你們可以提供一些建議。getline()不按預期工作

int main() 
{ 
    int students = 0; 
    students = getStudents(students); 

    int quizzes = 0; 
    quizzes = getQuizzes(quizzes); 

    string studentArray[50]; 
    int* quizArray = new int[quizzes]; 
    double* studentAverage = new double[students]; 
    string studentName = ""; 
    for(int i = 0; i < students; i++) 
    { 
     cout << "Enter the students name: "; 
     getline(cin, studentName); 
     studentArray[i] = studentName; 
     cout << studentName; 

     for(int j = 0; j < quizzes; j++) 
     { 
      cout << "Enter quiz " << j+1 << ":"; 
      cin >> quizArray[j]; 
     } 
     studentAverage[i] = calculateAvergage(quizArray,quizzes); 
     cout << studentArray[i]; 
     cout << studentName; 
    } 
    cout << endl; 
    cout << "Student    Quiz Average" << endl << endl; 
    cout << "---------------------------------" << endl << endl; 


    for(int i = 0; i < students; i++) 
    { 
     cout << studentArray[i]; 
     cout << setw(10) << studentAverage[i] << endl << endl; 
    } 
} 
int getStudents(int students) 
{ 
    cout << "How many students? "; 
    cin >> students; 
    cout << endl; 
    if(students > 50) 
    { 
     cout << "Invalid number of students, enter a number less than 50: "; 
     cin >> students; 
     cout << endl; 
    } 
    return students; 
} 
int getQuizzes(int quizzes) 
{ 
    cout << "How many quizzes? "; 
    cin >> quizzes; 
    cout << endl; 
    if(quizzes > 10) 
    { 
     cout << "Invalid number of quizzes, enter a number less than 10: "; 
     cin >> quizzes; 
     cout << endl; 
    } 
    return quizzes; 
} 
double calculateAvergage(int quiz_array[],int num_quizzes) 
{ 
    double average = 0; 
    for(int i = 0; i < num_quizzes; i++) 
    { 
     average = quiz_array[i] + average; 
    } 
    average = (average/num_quizzes); 
    return average; 
} 
+0

'cin'可能處於失敗狀態,**發佈完整示例**。 – user657267 2014-10-29 00:33:28

+0

根據請求發佈整個程序 – user3558697 2014-10-29 00:36:08

+0

[C++ getline方法不工作]可能的重複(http://stackoverflow.com/questions/19257205/c-getline-method-not-working) – 2014-10-29 00:37:12

回答

0

從流讀取單個值這樣

cin >> quizzes; 

不消耗行字符的後端(或試圖讀取quizzes後剩下的任何其他無效字符),所以下一次撥打getline將繼續從相同的輸入行讀取(通常您會預計該行在閱讀quizzes後爲空,因此getline最終不會讀取任何內容)。

你的程序工作,如果使用下面的閱讀quizzes之後:以同樣的方式

std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n'); 

或者你可以簡單地讀取studentName爲其他值

std::cin >> studentName; 

與所有來電operator>>這將刪除包括換行符在內的所有主要空白。