对“是”或“否”语句的回答无效

时间:2015-11-04 07:30:12

标签: 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;
    }

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

2 个答案:

答案 0 :(得分:2)

一个简单的解决方案:创建一个基本上可以循环循环的循环,一次又一次地问同一个问题,但是在一个有效的答案上打破它:

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;
}

答案 1 :(得分:0)

我想向你展示一些更复杂的灵魂,但我更喜欢这个,因为更容易修改可接受的答案。希望对你有帮助! 我还建议将用户输入转换为小写,以使acceptable向量的长度保持较低。

-EDIT-(感谢bolov

#include <iostream>
#include <string>
#include <algorithm>
#include <vector>

std::vector<std::string> acceptable = {"yes", "no", "unsure"};

int main() {
  std::string message;
  while(std::end(acceptable) == std::find(std::begin(acceptable), std::end(acceptable), message))
    std::cin >> message;
}

您也可以使用std::map将答案映射到用户输入。 Probaply你应该拨打accpt.find(msg)一次,但我认为在这种情况下这不是什么大问题:)

#include <iostream>
#include <string>
#include <map>

std::map<std::string, std::string> accpt = {
  {"yes", "yes was given"},
  {"no", "no was given"},
  {"unsure", "unsure was given"}
};

int main() {
  std::string msg;
  while(accpt.find(msg) == accpt.end())
    std::cin >> msg;
  std::cout << accpt.find(msg)->second;
}