gpt4 book ai didi

c++ - 如果用户输入无效则循环

转载 作者:太空宇宙 更新时间:2023-11-04 13:03:32 24 4
gpt4 key购买 nike

我想创建一个程序,当用户输入我没有定义的内容时,程序会再次提示他。

我用 if 语句完成了它,但它只循环了 1 次并且不再执行。我尝试了循环,但只要输入为假,它就会打破条件并拒绝所有输入。在 C++ 中。

非常感谢任何帮助。

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


void xD(){string x;
do{cout << "Retry\n";
cin >> x;}while(true);}
//declaring a function to make the shop
void shop(){
string x;
float coins = 500;
float bow_cost = 200;

cout << "welcome to the shop\n";

cout << "Bow(bow)costs 150 coins.\n";

cin >> x;
// if u chose bow you get this and get to choose again
if (x == "bow"){
cout << "you bought the bow.\n you now have " <<coins - bow_cost << " coins." << endl; cin >> x;}

/*now the problem that whenever I excute the code and type something other than bow it gives me the cin only once more and then fails even if I type bow in the 2nd attempt*/



//in my desperate 5k attempt, I tried creating a function for it.. no use.
//i want it o keep prompting me for input till i type "bow" and the other block excutes. but it never happens.
else{xD();}

}
int main(){
string name;
string i;

cout << "if you wish to visit the shop type \"shop\"\n";


cin >> i;


if(i == "shop"){shop();}
else{cin >> i;}
return 0;
}

最佳答案

问题出在这个循环 block 中的条件

void xD(){
string x;
do{
cout << "Retry\n";
cin >> x;
}while(true);
}

无论输入如何,while(true) 条件都会使其永远循环。要解决此问题,您可以更改条件:

void xD(){
string x;
do{
cout << "Retry\n";
cin >> x;
}while(x!="bow");
cout << "you bought the bow. and some other messages"<<endl;
}

那应该行得通。但是,这对我来说仍然太复杂了。这可以简化为以下代码段:

void shop(){
string x;
float coins = 500;
float bow_cost = 200;

cout << "welcome to the shop\n";

cout << "Bow(bow)costs 150 coins.\n";

cin >> x;
while (x!="bow"){
cout << "Retry\n";
cin>>x;
}
cout << "you bought the bow.\n you now have " <<coins - bow_cost << " coins." << endl; cin >> x;

}

关于c++ - 如果用户输入无效则循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43305674/

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