If then else条件被跳过
C++ If then else conditional being skipped
我正在为班级写一个程序。它将一个句子翻译成伪日语(使用英语单词,但按照语法顺序重新排列,并在相关单词后添加后缀)。
库是有限的,我们不能使用函数或数组(低级类)。在这种情况下,我输入的句子:
"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()
看到这正在发生。当使用cout
的operator<<
打印字符串时,额外的0字节没有影响,但它确实阻止了字符串与"red"
相等的比较。
相关文章:
- 为什么"do while"循环不断退出,即使条件计算结果为 false?
- 在没有太多条件句的情况下,我如何避免被零除
- 基于多个条件处理地图中的所有元素
- 条件constexpr函数
- 无论条件是否为true,if总是在c++中执行
- 我可以使用条件运算符初始化C风格的字符串文字吗
- 基于模板值的条件变量
- 多个If语句与使用逻辑运算符计算条件的单个语句的比较
- 将按位if条件转换为普通if条件
- 条件断点在不应该触发时触发
- 为什么简单的算术减法在"if"条件下不起作用?
- 如何在for循环中包含两个索引值的测试条件
- 如果条件为TRUE(最佳方式?),则在do while循环中后置增量
- 我提出什么条件才能再加5%的折扣
- 循环中的条件:为什么每次都调用strlen(),而vector.size()只调用一次
- 即使没有满足他们的条件,我也无法通过一些 do-while 循环
- 条件运算符vs if then else
- If then else条件被跳过
- 如何优化If/then条件表达式的长序列- SIMD
- C++:不应用于简单嵌套if-then-else语句的条件