【问题标题】:Do while loop.. right now: infinite, goal: not infinite (ask until loop) [duplicate]做while循环..现在:无限,目标:不是无限(询问直到循环)[重复]
【发布时间】:2021-03-17 15:32:03
【问题描述】:

所以当我输入一个字符或字符串时,它会再次询问这个问题,但会无限次......但我希望它每次错误时询问一次,如果错误则再次询问。得到它... ? :( 现在循环是无限的。

#include <iostream>
using namespace std;

int main() {
float money;

do
{
cout << "How much money do you have? " << endl;
cin >> money;

    if (money) {
       cout << "You have: " << money << "$" << endl;
    } else {
       cout << "You have to enter numbers, try again." << endl;
    }
} while (!money);

return 0;
}

【问题讨论】:

  • if (money) 等价于if(money != 0),它检查输入是否有效(您需要定义什么是有效输入)。它只检查money 的值,它总是一个数字。
  • 可能不是数字。当std::cin 应该将它们放入数字类型时键入字符串可能会导致这种情况发生。对于这种类型的验证,我通常建议将其作为字符串输入,并查看转换是否完全成功。
  • 这能回答你的问题吗? Good input validation loop using cin - C++ (虽然这取决于您是否只想验证某些输入、整行或其他内容。但这应该向您展示总体思路,尤其是关于清除和重置 cin 的部分)
  • 我希望用户输入$10 或类似的不是数字的东西。
  • 我以前没有见过重复的,我比我的字符串方法更喜欢它,因为它需要 try/catch。虽然,字符串方法可以“更严格”。 int 的输入可以使用 std::cin 方法接受 double

标签: c++ windows loops while-loop do-while


【解决方案1】:

您没有验证和清除cin 流的错误状态。试试这个:

#include <iostream>
#include <limits>
using namespace std;

int main() {
    float money;

    do
    {
        cout << "How much money do you have? " << endl;

        if (cin >> money) {
            // a valid float value was entered

            // TODO: validate the value further, if needed...

            break;
        }
        else {
            // an invalid float was entered

            cout << "You have to enter numbers, try again." << endl;

            // clear the error flag and discard the bad input...
            cin.clear();
            cin.ignore(numeric_limits<streamsize>::max(), '\n');
        }
    }
    while (true);

    cout << "You have: " << money << "$" << endl;

    return 0;
}

【讨论】:

  • 啊哈.. 非常感谢!
猜你喜欢
  • 2016-04-21
  • 2015-06-25
  • 1970-01-01
  • 1970-01-01
  • 2012-12-24
  • 2021-02-20
  • 2014-03-29
  • 1970-01-01
  • 2020-08-18
相关资源
最近更新 更多