首页 > 解决方案 > 在 C++ 中处理无效的用户输入

问题描述

我已经用 C++ 编码了几天,所以请像我是个婴儿一样跟我说话。有了这个,

我制作了一个简短的算法,它提出一组问题(回答为 0 表示否,1 表示是)并将用户的答案存储为整数。只要用户只输入整数(或者,在一种情况下,一个没有空格的字符串),一切都会按预期工作。

但是如果输入与变量类型不匹配,程序会立即输出这个在程序后面出现的无限循环。该循环应该打印一个问题,等待输入,然后再次询问答案是否不是“1”,但在失败状态下它只是打印没有结束的问题。我看不出前面的问题与此相关的任何原因。如果这是一个线索,它不会发生在它之后的问题上。

这是我的代码的精简版本,我希望所有重要信息都完好无损:

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

int main()
{
    int answer1;
    string answer1C;
    int answer2;
    int answer2B;
    int score;
    score = 0;

    cout << "Question 1" << endl;
    cin >> answer1;
    if (answer1 == 1)
    {
        ++score;
        //some other questions go here
        cout << "Question 1C" << endl;
        cin >> answer1C;
        if (answer1C.size() == 6)
        {
            ++score;
        }
    }

    cout << "Question 2" << endl;
    cin >> answer2;
    if (answer2 == 0)
    {
        cout << "Question 2B" << endl;
        cin >> answer2B;
        if (answer2B == 0)
        {
            --score;
        }
        while (answer2B != 1) //Here is the infinite loop.
        {
            cout << "Question 2B" << endl;
            cin >> answer2B;
        }
    }

    cout << "Question 3" << endl;
    //and so on

    return 0;
}

我希望它接受任何输入,并且仅在恰好满足指定条件时才执行后续步骤:例如,在问题 1.2 中,它在答案是长度为 6 的字符串时才奖励一分,否则什么也不做; 或者在问题 2.1 中,它对任何不是“1”的输入重复该问题,如果是,则继续。

但无论如何,当它失败时,我需要它做其他事情。请帮我弄清楚为什么会这样。谢谢你。

标签: c++loopsvariablesinput

解决方案


推荐阅读