gpt4 book ai didi

c++ - 如果用户输入的字符串变量无效,如何重复输入命令-C++

转载 作者:行者123 更新时间:2023-12-01 14:58:03 25 4
gpt4 key购买 nike

因此,我几乎没有编码经验,并且我编写的代码存在这样的问题:如果第一次正确选择"is",则要求用户再次输入。如果用户输入“否”,或者如果用户输入了无效的选项,它将正常工作,下一组问题将起作用。我没有找到任何不使用数组处理字符串变量的示例。谢谢 -
附言我知道它的形状很烂,但是我只是想让它正常工作。

#include<string>
#include<iostream>

using namespace std;

int main() {
string choice;

cout<<"Do you choose to go fight in the war??\n\n";
cout << "choose yes or no\n";
cin >> choice;

while(choice != "yes" || choice != "no")
{
cout << "pls enter again\n";
cin >> choice;
if(choice == "no")
{
cout << "you live";
break;
}
else(choice == "yes");
{
cout << "you die";
break;
}
}
}

最佳答案

当我开始学习编码时,遇到了同样的逻辑问题,例如您目前正在努力的问题。我只是认为您在语法和编码逻辑方面遇到问题。希望我的代码可以以某种方式提供帮助!

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

int main() {
string choice;

do {
cout << "Do you choose to go fight in the war??\n";
cout << "Choose yes or no\n";
cin >> choice;

if (choice == "no") {

cout << "you live\n";
break;

} else if (choice == "yes") {

cout << "you die\n";
break;
}

} while (choice != "yes" && choice != "no");

return 0;
}

关于c++ - 如果用户输入的字符串变量无效,如何重复输入命令-C++,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60360803/

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