c ++中循环的奇怪问题

Strange trouble with a loop in c++

我刚开始在学校学习编程。我一直在让我的代码拒绝来自用户的非数字 cin 时遇到问题。我想出了一种方法,但现在当我输入一个数字时,这种奇怪的事情发生了,我必须插入有效输入 3 次,然后它才能通过循环清除并继续程序的下一部分。

//要转换的数量

if (exchangeRate == JAPANESE_EXCHANGE_RATE)
{
    cout << "How many " << currencyName << " do you need a conversion for?" << '\n' << '\n';
}
else
{
    cout << "How many " << currencyName << "s do you need a conversion for?" << '\n' << '\n';
}
do
{
    cin >> conversionAmount;
    cout << '\n' << '\n';
    if (conversionAmount > -1)
    {
        cout << '\n'; // nothing needs to be done, the number will be accepted and proccessed;
    }
    else if (!(cin >> conversionAmount) || conversionAmount < 0)
    {
        cin.clear();
        cin.ignore(10000000000000, '\n');
        cout << "That value does not work; try again";
        cout << '\n' << '\n';
    }
}
while (!(cin >> conversionAmount));

这只是代码中出现问题的部分;它运行完美,除了我必须以一种奇怪的方式将它从循环中解救出来。如果您需要更多代码,我很乐意 post 它。我刚开始学习编程,所以如果你也能解释我错误背后的逻辑,那将对我有很大帮助。

每次执行 cin >> conversionAmount 时,您的输入流 (cin) 都在等待输入。如果您查看您的代码,您的循环中有 4 cin >> conversionAmount。因此,您需要输入 4 次才能进入下一次迭代。

但是,总的来说,最好使用字符串流而不是直接从 cin 读取。看看这个 Tutorial

As you can see, extracting from cin seems to make the task of getting input from the standard input pretty simple and straightforward. But this method also has a big drawback. What happens in the example above if the user enters something else that cannot be interpreted as an integer? Well, in this case, the extraction operation fails. And this, by default, lets the program continue without setting a value for variable i, producing undetermined results if the value of i is used later.

This is very poor program behavior. Most programs are expected to behave in an expected manner no matter what the user types, handling invalid values appropriately. Only very simple programs should rely on values extracted directly from cin without further checking. A little later we will see how stringstreams can be used to have better control over user input.