如何在C ++中检查有效的用户输入 [英] How to check for a valid user input in C++

查看:43
本文介绍了如何在C ++中检查有效的用户输入的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试打造公牛队.C ++中的Cows游戏.我已经实现了大多数逻辑.该游戏使用无限循环连续运行,并在每次运行时生成一个随机值.

I'm trying to build the Bulls & Cows game in C++. I've implemented most of the logic. The game runs continuously with the use of an infinite loop and generates a random value at each run.

我现在要尝试的是获取用户输入并在输入有效的情况下运行代码(只能为4位整数).这是我的实现:

What I'm trying to do now is to now is to take the user input and run the code if the input is valid (can ONLY be a 4 digit integer). This is my implementation:

#include ...

using namespace std;

vector<int> getDigits(int modelValue) {
    vector<int> vectorValue;
    int extractedDigit = 0;
    int modulant = 10000;
    int divisor = 1000;

    for (int i = 0; i < 4; i++) {
        extractedDigit = (modelValue % modulant) / divisor;
        vectorValue.push_back(extractedDigit);
        modulant /= 10;
        divisor /= 10;
    }return vectorValue;
}


int main() {
    for (;;) {
        int model = rand() % 9000 + 1000;
        int guess = 0000;
        int bulls = 0;
        int cows = 0;
        int counter = 1;

        cout << "This is the random 4-digit integer: " << model << endl;
        cout << "Enter a value to guess: ";
        cin >> guess;

        if ((guess >= 1000) && (guess <= 9999) && (cin)) {

            vector<int> modelVector = getDigits(model);
            vector<int> guessVector = getDigits(guess);

            for (int i = 0; i < 4; i++) {

                if (find(modelVector.begin(), modelVector.end(), guessVector[i]) != modelVector.end()) {
                    if (modelVector[i] == guessVector[i]) { bulls += 1; }
                    else { cows += 1; }
                }
            }cout << "There are " << bulls << " bulls and " << cows << " cows" << endl;
        }
        else {
            cout << "Please enter a valid 4-digit integer between 0000 and 9999" << endl;
            cin.clear();
        }
    }return 0;
}

但是当我运行并输入无效内容时,得到的是连续运行的.

But when I run and input something invalid, what I get is a continuously running .

推荐答案

读取用户输入的方式没有任何问题,只是在将值分配给"guess"变量之前不检查输入类型.

There's nothing wrong with the way you read the user input, it just doesn't check for the input type before assigning the value into your 'guess' variable.

因此,如果用户放置了整数类型不接受的任何值,则将导致生成此无限循环的应用程序崩溃.

So, if an user put any value that isn't accepted by the integer type it would crash your application generating this infinite loop.

要保护整数变量免受错误的用户输入,您必须替换直接输入分配:

To protect your integer variable from wrong user inputs you must replace your direct input assignment:

cin >> guess;

由受保护的人

while(!(cin >> guess) || (guess < 1000)){
    cin.clear();
    cin.ignore(numeric_limits<streamsize>::max(), '\n');
    cout << "Invalid input. Please, try again: ";
}

在上面的 while 中,您可以看到"numeric_limits :: max()",其中解释了

Into the while above you can see the "numeric_limits::max()" which is explained here:

返回由数字类型T表示的最大有限值.对于所有有界类型都有意义.

Returns the maximum finite value representable by the numeric type T. Meaningful for all bounded types.

最后,您有一个 while ,让用户进入该阅读循环,而其输入值小于1000(根据要求)或不是有效的整数.

At the end you have a while holding the user into this reading loop while its input is under 1000 (as requested) or isn't a valid integer.

这篇关于如何在C ++中检查有效的用户输入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆