如果用户输入无效,如何使用字符串变量-C++重复输入命令
How to repeat input command if user input is invalid with a string variable - C++
所以我几乎没有编码经验,而且我编写的代码存在这样的问题,即如果第一次正确选择"是",就会要求用户再次输入。如果用户输入"否",或者如果用户写了一个无效的选项,那么下一组问题就会起作用。我还没有发现任何不使用数组处理字符串变量的例子。谢谢-附言:我知道它的糟糕形式,但我只是想让它发挥作用。
#include<string>
#include<iostream>
using namespace std;
int main() {
string choice;
cout<<"Do you choose to go fight in the war??nn";
cout << "choose yes or non";
cin >> choice;
while(choice != "yes" || choice != "no")
{
cout << "pls enter againn";
cin >> choice;
if(choice == "no")
{
cout << "you live";
break;
}
else(choice == "yes");
{
cout << "you die";
break;
}
}
}
您需要的不是else
而是else if
:
else if (choice == "yes") {
cout << "you die";
break;
}
using namespace std;
int main()
{
string choice;
cout << "Do you choose to go fight in the war??nn";
cout << "choose yes or non";
while (true) {
cin >> choice;
if (choice == "no") {
cout << "you live";
break;
}
else if (choice == "yes")
{
cout << "you die";
break;
}
else {
cout << "pls enter againn";
}
}
return 0;
}
当我开始学习编码时,我面临着同样的逻辑问题,比如你现在正在挣扎的问题。我只是觉得你在语法和编码逻辑方面有问题。希望我的代码能有所帮助!
#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 non";
cin >> choice;
if (choice == "no") {
cout << "you liven";
break;
} else if (choice == "yes") {
cout << "you dien";
break;
}
} while (choice != "yes" && choice != "no");
return 0;
}
使用do-while循环进行字符串输入,循环后应用条件
#include<iostream>
using namespace std;
main()
{
String choice;
cout << "Do you choose to go fight in the war??nn";
cout << "choose yes or non";
do
{
cin >> choice;
If(choice != "yes" || choice != "no")
Cout<<"please enter again";
}
while (choice != "yes" || choice != "no");
If (choice == "no")
{
cout << "you live";
}
else
{
cout << "you die";
}
}
相关文章:
- 在C++程序中输入的文本文件将不起作用,除非文本被复制和粘贴
- 2D数组来自文本输入,中间有空格
- 如何使用 < 和 > 命令获取 c++ 中的输入和输出?
- 检查输入是否不是整数或数字
- 正在尝试了解输入验证循环
- 读取文件并输入到矢量中
- C++如何通过用户输入删除列表元素
- 用c++从输入文件中读取另一行
- 读取文件的最后一行并输入到链接列表时出错
- 创建一个函数以在输入为负数或零时输出字符串.第一次执行用户定义的函数
- 如何使用用户输入在C++中正确填充2D数组
- C++MySQL C api用户输入行
- 输入到文件并输出到另一个文件,并将流文件传递给函数
- 用户定义函数中的指针和输入
- 如何在C++中检查2D数组中负值的输入验证
- 如何只允许用户输入正整数
- 在while循环中输入带有std::cin的字符串后,控制台会输出大量胡言乱语
- 输入中的字符串数未知(以字母表示)
- cpp二进制搜索问题,计算给定数组中输入元素的出现次数
- 在一个模板函数中,若输入的类型是enum类,我该如何使用std::underlying_type