C++正在检查用户是否输入了有效答案

C++ Checking if a user input a valid answer

本文关键字:输入 有效 答案 是否 用户 检查 C++      更新时间:2023-10-16

当提示时,我需要检查他们是否输入了快乐、悲伤或疯狂:输入心情(快乐、悲伤、疯狂)这是我迄今为止的代码count=0;而(计数<1){

    cout << ", How are you feeling today? (happy,sad,mad)" << endl;
    cin >> mood;
    if (mood == sad){
        cout << "im sorry you're feeling sad" << endl;
            count++;
    }
    else if (mood == happy) {
        cout << "I'm glad you're feeling happy!" << endl;
            count++;
    }
    else if (mood == mad){
        cout << "Don't be angry, there's so many happy things in life!" << endl;
    }
    else{
        cout << " invalid input " << endl;
        count = 0;
    }
    }

但如果我输入快乐、悲伤或疯狂,它就会进入无效输入。我还尝试为它们声明字符串变量,比如string happy=快乐;string sad=悲伤;string mad=疯狂;

两件事:

  1. 确保您正在正确初始化字符串的

    string happy = "happy";
    
  2. 尝试使用string.compare()而不是==

    mood.compare(happy);
    

有关更多详细信息:http://www.cplusplus.com/reference/string/string/compare/