gpt4 book ai didi

c++ - 如何在 C++ 中检查有效的用户输入

转载 作者:塔克拉玛干 更新时间:2023-11-03 00:46:35 25 4
gpt4 key购买 nike

我正在尝试用 C++ 构建 Bulls & Cows 游戏。我已经实现了大部分逻辑。游戏使用无限循环连续运行,并在每次运行时生成一个随机值。

我现在要做的是获取用户输入并在输入有效时运行代码(只能是 4 位整数)。这是我的实现:

#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;
}

但是当我运行并输入一些无效的东西时,我得到的是一个连续运行的 console .

最佳答案

您读取用户输入的方式没有任何问题,它只是在将值分配给您的“猜测”变量之前不检查输入类型。

因此,如果用户输入任何整数类型不接受的值,它会使您的应用程序崩溃,从而产生这个无限循环。

为了保护您的整数变量免受错误用户输入的影响,您必须替换您的直接输入赋值:

cin >> guess;

protected 者:

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

在上面的 while 中,您可以看到解释为“numeric_limits::max()”的 here :

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

最后,当用户的输入低于 1000(根据要求)或不是有效整数时,while 让用户进入此阅读循环。

关于c++ - 如何在 C++ 中检查有效的用户输入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50373923/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com