c++ - 对是或否陈述的无效回答

标签 c++

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

string mood;

int main()
    {
        cout << "Are you feeling happy today?" << endl;
        cin >> mood;
        if (mood == "yes" || mood == "Yes")
            {
                cout << "Great! Glad you're happy!" << endl;
            }
        if (mood == "no" || mood == "No")
            {
                cout << "That's unfortunate, hope you feel better." << endl;
            }
        if (mood == "unsure" || mood == "Unsure")
            {
                cout << "At least you're alive!" << endl;
            }
        else
            cout << "Please answer with 'yes', 'no' or 'unsure'" << endl;

            // How would I make this loop back to asking the user the
            // "Are you feeling happy today" again?

    return 0;
    }

我想知道在"is"或“否”问题中,如果用户输入"is"或“否”以外的任何内容,我是否能够循环回到向用户询问初始问题。我需要一个 while 循环吗?如果是这样,有人可以解释一下吗?

最佳答案

一个简单的解决方案:制作一个基本上可以永远循环的循环,一次又一次地问同样的问题,但在出现有效答案时打破它:

int main()
{
    string mood;

    while(1)
    {
        cout << "Are you feeling happy today?" << endl;
        cin >> mood;
        if (mood == "yes" || mood == "Yes")
        {
            cout << "Great! Glad you're happy!" << endl;
            break;
        }
        if (mood == "no" || mood == "No")
        {
            cout << "That's unfortunate, hope you feel better." << endl;
            break;
        }
        if (mood == "unsure" || mood == "Unsure")
        {
            cout << "At least you're alive!" << endl;
            break;
        }

        cout << "Please answer with 'yes', 'no' or 'unsure'" << endl;
    }

    return 0;
}

关于c++ - 对是或否陈述的无效回答,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33516074/

相关文章:

c++ - tlb 文件是否具有关联架构?

C++ 冒泡排序和比较

C++ 和 SDL : Why can't I compile this program?

c++ - C++ 编译器会通过 `reference` 优化掉未使用的返回值吗?

c++ - 如何从 C++ 设置和读取并行端口上的引脚?

c++ - 防止定义某些模板

c++ - std::piecewise_construct 不会导致 ODR 违规吗?

c++ - 为什么 NRVO 在下面的代码中启动 g++?

c++ - 错误:没有匹配的函数可用于调用 > ‘std::vector<MemberListEntry>::push_back 和

c++错误访问boost fusion 对中的字段类型