我正在编写一个游戏,电脑必须猜出你想要的数字。只有当您第一次输入错误的字符串时,我的数据清理才有效。假设第二次数据清理中断时输入了一个错误的字符串。有人知道怎么解决这个问题吗?
#include <iostream>
#include <string>
using namespace std;
int main() {
string hint, play;
int max = 100, min = 0, tries=0, num;
bool again;
again = true;
while(again = true){
num = (max + min) / 2;
cout<< "The computer's guess is: " << num << endl;
cout << "Is your number higher, lower, or correct?: ";
cin >> hint;
if(hint !="lower"){
if(hint != "higher"){
if(hint!="correct"){
cout << "Is your number higher, lower, or correct?: ";
cin >> hint;
tries++;
if (hint == "higher")
min = num + 1;
else if (hint == "lower")
max = num - 1;
cout << "The computer's guess was correct after " << tries<<endl;
}while(hint != "correct");
cout << "do you want to play again?(y/n): ";
cin>>play;
if(play!="y"){
if(play!="n"){
cout << "do you want to play again?(y/n): ";
cin>>play;
if(play == "y"){
again = true;
if(play == "n"){
cout<<"thank you for playing";
break;
}
发布于 2022-10-08 02:18:13
您需要使用while循环而不是嵌套的if语句。这样,我们就可以等到用户决定输入正确的输入。此外,通常情况下,最好将用户的输入转换为小写,并删除空格,以防他们键入类似于此
" CorRecT"
的内容。用户将永远不会按一般经验规则准确地键入您期望他们的内容。
我提供的代码需要包含
<algorithm>
才能正常工作。如果您由于某种原因无法添加它,只需删除以
transform
开头的行。如果这样做,字符串将不会被删除。
我还将行
while (again = true)
更改为
while (again)
。使用
=
运算符将
again
的值设置为
true
,我认为这是无意的。
==
操作符可能就是你要找的东西。但是,在任何if语句或循环中都没有必要检查
true
是否相等,因为如果条件等于true,则循环将始终运行。
while (again) {
num = (max + min) / 2;
cout << "The computer's guess is: " << num << endl; \
bool invalidInput = true;
while (invalidInput) {
cout << "Is your number higher, lower, or correct?: ";
cin >> hint;
// Remove whitespace and convert hint to lowercase
hint.erase(remove_if(hint.begin(), hint.end(), isspace), hint.end());
transform(hint.begin(), hint.end(), hint.begin(), [](unsigned char c) { return tolower(c); });
// Validate the input
if (hint == "higher" || hint == "lower" || hint == "correct") {