while 循环中的多个条件使用 &&&
Multiple conditions in while loop using &&
工作原理:
ifstream in("CallHello.cpp");
while(in >> s) {
if(s=="cout")
count++;
}
cout<<"Number of words : "<<count<<endl;
此处的输出为1,这是正确的。
什么不起作用
ifstream in("CallHello.cpp");
while(in >> s && s == "cout") {
count++;
}
cout<<"Number of words : "<<count<<endl;
输出为0,以上错误。
为什么在使用&;给出错误的输出?
当in
有东西要放在s
上时,第一个条件将继续循环,如果第一次为s
检索值时有一个"cout"
字符串,则使用while(in >> s && s == "cout")
的第二个条件将仅起作用,因此,s
中的第一个值第一次不是"cout"
,因此它永远不会循环。
原因如下:
string s;
int count = 0;
while (in >> s && s == "cout") { // Ops: s == ""
++count; // while condition is false!
} // loop is skipped!
cout<<"Number of words : "<<count<<endl; // count was never incremented
// Output is 0
相关文章:
- 如何在for循环中包含两个索引值的测试条件
- 如果条件为TRUE(最佳方式?),则在do while循环中后置增量
- 循环中的条件:为什么每次都调用strlen(),而vector.size()只调用一次
- 即使没有满足他们的条件,我也无法通过一些 do-while 循环
- 在循环条件 i<sqrtN(预先计算)和 i*i<N 中,C++哪个更有效?
- 尽管条件为真,循环仍停止
- 为什么我不能在 for 循环中出现这样的条件?(C++)
- C++ 即使不满足条件,循环也会终止
- 具有迭代器和自定义步长的循环结束条件
- 有没有办法在循环中的条件至少满足一次时运行语句?
- 为什么循环没有中断,并且 if 条件没有按预期工作?
- 为什么我不能将 size() 函数编写为 while 循环中的条件?
- 虽然循环即使应用了错误条件也不会退出
- 当循环在条件C++之前停止工作时
- Leetcode C++用于循环条件
- 当满足条件时,While循环未结束
- 对于检查 >=0 终止条件时的循环索引类型
- 调用以条件循环(c++)
- 使用布尔条件c++循环时无法退出
- 在条件C++循环语句中向SQLite3表中插入条目