2010-04-25 121 views
0

正如問題所述,出於某種原因,我的程序並未以目前無法識別的方式刷新輸入或使用變量。這是一門功課的項目,我已經超過了我爲它做,現在我只想程序實際工作:P輸入未清除

細節,使查找更容易:

程序執行完美無缺在第一次通過。所有拋出工作,只有適當的值(n> 0)被接受並變成二進制。

只要輸入我的終止輸入,程序進入一個循環,並只要求等,從而再次終止:

當我在我的Linux筆記本電腦上運行Netbeans的這個程序,我輸入終止值後程序崩潰。在Windows上的Visual C++中,它像上面描述的那樣進入循環。

在代碼中,我嘗試清除每個流,並在程序重新啓動時初始化每個變量,但無濟於事。我只是看不到我的錯誤。

我相信躺在無論是在主函數的錯誤:

int main(void) 
{ 
vector<int> store; 
int terminate = 1; 

do 
{ 
    int num = 0; 
    string input = ""; 

    if(cin.fail()) 
    { 
     cin.clear(); 
     cin.ignore(numeric_limits<streamsize>::max(), '\n'); 
    } 

    cout << "Please enter a natural number." << endl; 
    readLine(input, num); 

    cout << "\nThank you. Number is being processed..." << endl; 
    workNum(num, store); 

    line; 
    cout << "Go again? 0 to terminate." << endl; 
    cin >> terminate // No checking yet, just want it to work! 

    cin.clear(); 
}while(terminate); 

cin.get(); 
return 0; 
} 

或在讀取號碼的功能:

void readLine(string &input, int &num) 
{ 
    int buf = 1; 
    stringstream ss; 
    vec_sz size; 

    if(ss.fail()) 
{ 
     ss.clear(); 
    ss.ignore(numeric_limits<streamsize>::max(), '\n'); 
} 

    if(getline(cin, input)) 
    { 
     size = input.size(); 
     for(int loop = 0; loop < size; ++loop) 
      if(isalpha(input[loop])) 
       throw domain_error("Invalid Input."); 

    ss << input; 
    ss >> buf; 

    if(buf <= 0) 
     throw domain_error("Invalid Input."); 

    num = buf; 

    ss.clear(); 
    } 
} 

回答

2

當你調用cin >> terminate,它會讀取的值終止,但在輸入流中保留下一個換行符。當你打電話給getline(cin, input)時,它會讀到換行符,這意味着它會得到一個空字符串。

您可以通過cin >> terminate後添加此放棄所有字符,直到達到新行:

cin.ignore(99, '\n'); 

或避免混合operator >>getline

+0

AAAAH,我認爲如果(cin.fail())將清除流,但是啊,這是一個邏輯錯誤^^謝謝! – IAE 2010-04-25 12:42:30

2

不要混合那些>>getline運營商作爲interjay提到。 另外,如果你想清楚你的代碼,我認爲它可以改寫的folllowing方式:

int main() { 
    while (true) { 
     std::cout << "Please enter a natural number" << std::endl; 
     int num; 
     std::cin >> num; 

     // Exception handling here can be done easily 
     // like this 
     // if (!(std::cin >> num) || num < 0) 
     // throw std::domain_error("TROLOLOLO"); 

     std::cout << "Thank you. Number is being processed..." << std::endl; 
     //workNum(num, store) here 

     std::cout << "Go again? 0 to terminate." << std::endl; 

     int terminate; 
     std::cin >> terminate; 
     if (terminate == 0) break; 
    } 
}