【问题标题】:Immediate exit of a loop when input is not an unsigned in C++当输入不是 C++ 中的无符号时立即退出循环
【发布时间】:2016-01-19 13:17:10
【问题描述】:

我的代码是:

unsigned numbers, x = 0, odds = 0;
cout << "Input numbers to find the amount of odds. " << endl;
while ( x < 9999 ){
    cin >> numbers || die("Input Error");
    if (numbers % 2 == 1) {
        odds++;
    }
}
cout << "There are " << odds << " odds." << endl;

return 0;

当用户输入数字的非数字值时,如何退出循环?提前谢谢你。

【问题讨论】:

标签: c++ loops


【解决方案1】:

您可以将输入作为循环的条件。

while (cin >> numbers)
{
    //...
}

将一直运行,直到用户输入无法输入到numbers 的内容。如果您也想检查numbers &lt; 9999,那么我们将拥有

while (std::cin >> numbers && numbers < 9999)
{
    //...
}

【讨论】:

  • 这是不正确的。见:stackoverflow.com/questions/7465494/…
  • @Nandu 什么?这与此无关,这是错误的语言。
  • @Nandu 问题是“当用户输入数字的非数字值时,如何退出循环?” “123a”怎么算数值?
  • @Nandu 会拾取 123 处理后终止。这与 OP 在不进行大量字符串处理的情况下可以获得的一样好。
【解决方案2】:

您要查找的关键字是break

while ( x < 9999 ) {
    if((cin >> numbers).fail())
        break;

    if (numbers % 2 == 1) {
        odds++;
    }
}

【讨论】:

【解决方案3】:
#include <cctype>
std::string str;
cin >> str;
for ( std::string::iterator it=str.begin(); it!=str.end(); ++it)
 if (!std::isdigit(*it)) {
   cout << "non-digit");
   return;
}

【讨论】:

    【解决方案4】:

    使用 hash_fun 计算字符串并忽略任何非数值

    【讨论】:

    • 什么是hash_fun 以及如何使用它?请改进您的答案。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-06-09
    • 2018-12-21
    • 1970-01-01
    • 2020-11-13
    • 1970-01-01
    相关资源
    最近更新 更多