【问题标题】:Problem with input in c++c++中的输入问题
【发布时间】:2011-02-23 20:49:27
【问题描述】:

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

我的代码是这样的

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

我只能使用 c++ 库而不是 c 库。

【问题讨论】:

标签: c++


【解决方案1】:

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

可能的实现:

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

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

【讨论】:

  • 不幸的是,这并不能真正检查初始读取是否成功:-(.
  • 您可能还应该清除标志,而不是在失败 && !eof 时跳出循环(输入字符串而不是数字时会发生这种情况)。
【解决方案2】:

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

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));

【讨论】:

    【解决方案3】:
    #include <locale>
    ..
    if(!isalpha(intInput)) { 
    ..
    }
    

    注意,如果用户输入一个“+”,这将不起作用,但它可能会让你朝着正确的方向前进..

    【讨论】:

    • intInput 显然是整数,所以不能在上面使用isalpha
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-09-06
    • 1970-01-01
    • 1970-01-01
    • 2023-03-30
    • 1970-01-01
    相关资源
    最近更新 更多