while 循环中的多个条件使用 &&&

Multiple conditions in while loop using &&

本文关键字:条件 循环 while      更新时间:2023-10-16

工作原理:

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,以上错误。

为什么在使用&amp;给出错误的输出?

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