2015-09-14 128 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; 
} 
相关问题