2015-09-14 122 views
-6

我是C++新手,嘗試創建一個程序,用戶在其中輸入想要的項目數量的整數值。當程序以int值運行時,當輸入像'2.2,1.34a,b5'這樣的值時它不起作用。C++:如何檢查輸入是否只是一個int?

這是我的計劃至今:

int main(){ 
     int nuts, bolts, screws; 

     cout << "Number of nuts: "; 
     cin >> nuts; 

     cout << "\n\nNumber of bolts: "; 
     cin >> bolts; 

     cout << "\n\nNumber of screws: "; 
     cin >> screws; 

     system("cls"); 

     cout << "Nuts: " << nuts << endl; 
     cout << "Bolts: " << nuts << endl; 
     cout << "Screws: " << nuts << endl; 

     return 0; 
    } 

任何幫助,將不勝感激。謝謝

+3

查看如何它完成雙,http://stackoverflow.com/questions/10828937/how-to-make-cin-to-take-only-numbers – user1

+0

@ user657267,它不會工作用於像33d那樣的輸入 – user1

回答

3

當您需要對用戶輸入執行錯誤檢查時,最好創建一個函數來進行錯誤檢查。

int readInt(std::istream& in) 
{ 
    int number; 
    while (! (in >> number)) 
    { 
    // If there was an error, clear the stream. 
    in.clear(); 

    // Ignore everything in rest of the line. 
    in.ignore(std::numeric_limits<std::streamsize>::max(), '\n'); 
    } 

    return number; 
} 

,然後,使用:

bolts = readInt(std::cin); 

如果你想擺脫困境,當用戶提供錯誤的輸入,你可以使用:

if (!(cin >> bolts)) 
{ 
    std::cerr << "Bad input.\n"; 
    return EXIT_FAILURE; 
} 
相關問題