在c ++中输入问题

时间:2011-02-23 20:49:28

标签: c++

我有一个非常基本的问题,我想在用户的某个范围内获取整数输入。如果用户给出一些字符串或char而不是整数。然后我的程序进入无限循环。

我的代码是那样的

cin >> intInput; 
while(intInput > 4 || intInput < 1 ){ 
   cout << "WrongInput "<< endl; 
   cin >> intInput; 
}

我只允许使用c ++库而不是c库。

3 个答案:

答案 0 :(得分:1)

正如possible duplicate中所述,您应该检查每个循环上cin的状态。

可能的实施:

if(cin >> intInput)
while(intInput > 4 || intInput < 1 ){ 
   cout << "WrongInput "<< endl; 
   if(!(cin >> intInput)){ break; } 
}

非常难看的代码,只是试图阐明检查cin状态的答案。

答案 1 :(得分:0)

此答案的解决方案是始终从标准输入中读取

std::string input; int value = 0;
do
{
        // read the user's input. they typed a line, read a line.
    if ( !std::getline(std::cin,input) )
    {
        // could not read input, handle error!
    }

        // attemp conversion of input to integer.
    std::istringstream parser(input);
    if ( !(parser >> value) )
    {
        // input wasn't an integer, it's OK, we'll keep looping!
    }
}
    // start over
while ((value > 4) || (value < 1));

答案 2 :(得分:-1)

#include <locale>
..
if(!isalpha(intInput)) { 
..
}

请注意,如果用户输入“+”但这可能会让您朝着正确的方向前进,那么这将不起作用。