程序跳过true if语句,但执行false语句

时间:2015-08-22 10:10:35

标签: c++ if-statement

好吧,所以我(尝试)做一个猜​​词游戏,同时也试图学习编码。我的问题是,程序跳过真正的if语句并执行false语句。这是一个部分:

#include <iostream>
#include <stdlib.h>

/*Some more #include...*/

using namespace std;

int main()
{
        int Lives = 5, Sel_Word, i;
        string Sel_Diff;

        /*Some more variables*/

        while(Lives >= 1)
        {
                cout << "Difficulty...";
                cin >> Sel_Diff;
                if  (Sel_Diff == "Very Easy")
                {

                        /*Executes game for that level*/

                }

                /*Gets skipped, when I enter "Very Easy" for
                some reason*/

                if (Sel_Diff == "Exit")
                {
                        break;
                }

                /*Works fine*/

                if (Sel_Diff == "Easy" || Sel_Diff == "Medium")

                /*Et cetera...*/

                {
                        cout << "\n\nDifficulty does not yet     exist!";
                }
                else
                {
                        cout << "\n\nDifficulty does not exist";
                }

                /*These two execute, when I enter 
                "Very Easy" for some reason*/

        }
}

注意: 我查看是否有人遇到同样的问题,但我没有找到任何人,虽然我发现了一个关于执行错误陈述的问题,这对我没有帮助。另外,我不知道这是否仅在c ++中发生,没有使用过c或c#。

1 个答案:

答案 0 :(得分:5)

这个条件

cin >> Sel_Diff;
if  (Sel_Diff == "Very Easy")

永远不会触发,因为operator>>一次只能读取一个单词。所以它在Very之后停止。

如果您想要阅读更多内容,例如整行输入,您可以使用getline(cin, Sel_Diff);

相关问题