程序跳过真if语句,但执行假if语句

Program skipping true if-statements, but executing false ones

本文关键字:语句 if 执行 程序      更新时间:2023-10-16

好的,所以我(试着)做一个猜字游戏,同时也试着学习编码。我的问题是,程序跳过了真if语句,执行了假if语句。这里有一个section:

#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 << "nnDifficulty does not yet     exist!";
                }
                else
                {
                        cout << "nnDifficulty does not exist";
                }
                /*These two execute, when I enter 
                "Very Easy" for some reason*/
        }
}

指出:我看了看是否有人有同样的问题,但我没有找到任何人,尽管我发现了一个关于虚假陈述执行的问题,这对我没有帮助。此外,我不知道这是否只发生在c++中,我没有用过c或c#。

此条件

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

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

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