2016-10-25 50 views
0

我目前正在編寫一個程序,需要除了一個選項,然後是一段文本,如果一段文本。如果文本是真的,那麼一段代碼執行?至少我認爲這就是它的工作原理,然而,程序直接到else並且因爲初始條件而不斷循環,所以它不會詢問用戶的另一個輸入是getline()?爲什麼程序循環而不是要求輸入?

#include <iostream> 
#include <fstream> 
#include <string> 
#include <iomanip> 

using namespace std; 

int main() { 

    fstream gFile; 
    int choice; 
    string gb; 
    do { 
     cout << "Student Grade Book Info Program....\n"; 
     cout << "\tPlease Select an Option: (1 or 2) \n" << endl 
      << "\t1. Review Grades" 
      << "\n\t2. Quit" 
      << "\n\tChoose: "; 
     cin >> choice; 

     switch (choice) { 

     case 1: 
      cout << "\n\tPlease Enter the Name of the File you wish to View the Grades for: " << endl; 
      cout << "\n\tAvailable Grade Books: gradeBook\n" << 
      "\tType in the Grade Book you would like to view. "; 

      getline(cin, gb); 

      if (gb == "gradeBook") { 

       cout << "execute code..."; 

      } 
      else { 
       cout << "\nError there is no such entry in the system." << endl; 

      } 

     case 2: 
      break; 
     } 

    } while (choice != 2); 


    return 0; 
} 

回答

1
cin >> choice; 

這將讀取真實輸入的號碼。但是,在這裏輸入的數字後面跟着一個換行符,operator>>將不會讀取。

cout << "\n\tAvailable Grade Books: gradeBook\n" << 
     "\tType in the Grade Book you would like to view. "; 

     getline(cin, gb); 

getline()現在讀的是從之前operator>>遺留下來的,而不是等待輸入的下一行中輸入換行符。

這是一個常見的錯誤:混合operator>>std::getline()。雖然可以同時使用兩者,但必須採取其他步驟才能正確執行此操作。閱讀換行符終止文本行的最簡單和最簡單的方法是使用std::getline()。這就是它的目的。只需使用std::getline()即可隨時閱讀文字輸入。如果您想將其解析爲整數或其他內容,請構建一個std::istringstream並解析它。

+0

ahh我看到我修好了!有效!太棒了,非常感謝。 –

+0

解釋很好,但解決方案至今無關緊要。不,這不是一個好的解決方案,所以你在提取操作員之前限制了getline的使用! 'cin.flush()'和'cin.sync()'和'cin.ignore()'的作用是什麼? – Raindrop7

+0

'getline'和'std :: getline'有什麼區別??? !!!! – Raindrop7

0

這是因爲輸入緩衝區仍然包含換行符,所以這會影響您的案例getline中的下一個輸入。

混和使用提取運算符「>>」函數getline正確剛剛刷新輸入緩衝區自己:

在你的榜樣

補充:

//cin.sync(); // or 
    cin.ignore(1, '\n'); 

添加上述行的一個函數getline所以你的代碼之前的權利將看起來像:

cin.ignore(1, '\n'); // flushing the buffer 
getline(cin, gb); 
相關問題