【问题标题】:Accept only integer to input只接受整数输入
【发布时间】:2019-07-24 01:57:29
【问题描述】:

我发现这个类似的问题被问了很多次,但我仍然找不到适合我的解决方案。

就我而言,我想在用户输入 1 到 5 的数字时显示一些内容,当他输入错误的内容(如字符“3g”、“3.”、“b3”和任何浮点数)时给出错误.

我尝试了下面的代码,但它产生了很多其他问题。就像我输入3g3.5 一样,它只会占用3 而忽略其余部分,因此(!cin) 根本不起作用。

其次,如果我输入一个字符之类的东西,__userChoice 会自动转换为0,程序会打印出"Please select a number from 1 to 5." 而不是"Invalid input, please input an integer number.\n",这正是我想要的。

cout << "Please select: ";
cin >> __userChoice;
if (__userChoice > 0 && __userChoice < 5) {
    cout << "You select menu item " << __userChoice <<". Processing... Done!\n";
}
else if (__userChoice == 5) {
    Finalization(); //call exit
}
else if (__userChoice <= 0 || __userChoice > 5) {
    cout << "Please select a number from 1 to 5.\n";
}
else (!cin) {
    cout << "Invalid input, please input an integer number.\n";
}
cin.clear();
cin.ignore(10000, '\n');

【问题讨论】:

  • __userChoice 是保留标识符。您应该使用另一个变量名。

标签: c++ input int


【解决方案1】:

operator&gt;&gt; 不能保证在发生故障时输出一个有意义的整数值,但您在评估 __userChoice 之前不会检查故障,并且您的 ifs 的结构方式 else (!cin) 检查永远不会达到。但即使operator&gt;&gt; 成功,您也不会检查用户输入的内容是否不仅仅是一个整数。

要执行您的要求,您应该首先使用std::getline()std::cin 读取到std::string,然后使用std::istringstreamstd:stoi()(或等效项)将string 转换为带有错误检查的int

例如:

bool strToInt(const std::string &s, int &value)
{
    std::istringstream iss(s);
    return (iss >> value) && iss.eof();

    // Or:

    std::size_t pos;
    try {
        value = std::stoi(input, &pos);
    }
    catch (const std::exception &) {
        return false;
    }
    return (pos == input.size());
}

...

std::string input;
int userChoice;

std::cout << "Please select: ";
std::getline(std::cin, input);

if (strToInt(input, userChoice))
{
    if (userChoice > 0 && userChoice < 5)
    {
        std::cout << "You selected menu item " << userChoice <<". Processing... Done!\n";
    }
    else if (userChoice == 5)
    {
        Finalization(); //call exit
    }
    else
    {
        std::cout << "Please select a number from 1 to 5.\n";
    }
}
else
{
    std::cout << "Invalid input, please input an integer number.\n";
}

【讨论】:

  • 我根据您的方法找到了另一个解决方案,谢谢。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-03-26
  • 1970-01-01
  • 2016-10-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多