If then else条件被跳过

C++ If then else conditional being skipped

本文关键字:条件 then else If      更新时间:2023-10-16

我正在为班级写一个程序。它将一个句子翻译成伪日语(使用英语单词,但按照语法顺序重新排列,并在相关单词后添加后缀)。

库是有限的,我们不能使用函数或数组(低级类)。在这种情况下,我输入的句子:

"is man red"(不带引号)

程序正确解析单词。即每个单词周围没有空格。

我的代码

if (word1 == "is")
{
    question = "is-ka";
    //If the second word is a subject, assign it and continue
    //assigning the 3rd or 4th word as the object or adjective and kick out
    //an error if not
    if (word2 == string("man") || word2 == string("woman") || word2 == string("fish"))
    {
        subject = word2 + "-ga";
        if (word3 == "man" || word3 == "woman" || word3 == "fish")
        {
            object = word3 + "-o";
            sentence = subject + ' ' + object + ' ' + question;
            cout << sentence << endl;
        }
        if (word3 == "red" || word3 == "short" || word3 == "strong")
        {
            adj = word3;
            sentence = subject + ' ' + adj + ' ' + question;
            cout << sentence << endl;
        }
        else
        {
            cout << "This is not a proper Eng-- sentence." << endl;
            cout << "2 The sentence lacks a proper object." << endl;
        }
    }

我测试第一个单词是否为'is',因为这是我们唯一可以使用的问题格式。如果这是一个问题,我就会找出句子中必须存在的主语、宾语和形容词,这样句子才会在语法上正确。

"is man red"的第一个和第二个条件通过了,但是当"is man red"的条件测试第三个单词是否为"red"时,它会跳到else语句并显示错误。

当条件应该为真时,为什么会跳过?

运行示例:

Enter an Eng-- sentence you would like to translate
is man red 
These are the words collected
Spaces after the colons and period at end of word are added.
First word: is.
Second word: man.
Third word: red.
This is not a proper Eng-- sentence.
2 The sentence lacks a proper object.

我希望这是你们一直在要求的。完整的代码并使用上面的输入编译

http://ideone.com/qPgM14

这里的问题是word3并不完全包含它看起来的内容,以一种特别令人困惑的方式。读取它的代码看起来像这样

//Word 3
   while(userSent[index] != ' ' && index <= sentLength)
    {
        word3 += userSent[index];
        index++;
    }

条件index <= sentLength应该是index < sentLength,因为c++字符串是从零开始索引的。对于<=,循环体也将终止零字节从userSent附加到word3。您可以通过检查word3.length()看到这正在发生。当使用coutoperator<<打印字符串时,额外的0字节没有影响,但它确实阻止了字符串与"red"相等的比较。