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

标签 c++ string loops if-statement user-input

因此,我几乎没有编码经验,并且我编写的代码存在这样的问题:如果第一次正确选择"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/

相关文章:

c++ - Qt 告诉我我的 SLOT 不存在,但是通过 make clean,让它不再提示

C++ boost 图 : How to customize callback function vf2_print_callback in vf2_subgrap_iso. hpp

c++ - Doxygen 可以与 Netbeans C++ 集成吗?

java - 使用 servlet 在从数据库读取和内存存储 Java 字符串之间进行权衡

matlab - 执行逐步积分

c++ - 数组初始化和查找字母频率

c++ - 将 unicode(?) 字符直接从源代码写入 WriteConsoleOutput

c# - 字符串到货币格式,没有句点(或逗号)

loops - Clojure 循环读取一个额外的

c++ - 进度条功能不循环