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

时间:2015-11-05 01:04:04

标签: c++ string

我需要在提示时检查他们是否输入快乐,悲伤或疯狂: 输入一种情绪(快乐,悲伤,疯狂) 到目前为止,这是我的代码 count = 0;     while(count< 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 = happy;     string sad = sad;     string mad = mad;

1 个答案:

答案 0 :(得分:-4)

两件事:

  1. 确保正确初始化字符串

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

    mood.compare(happy);
    
  3. 有关详情:http://www.cplusplus.com/reference/string/string/compare/