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

use*_*039 1 c++ while-loop

什么有效:

ifstream in("CallHello.cpp");
while(in >> s) {
    if(s=="cout")
        count++;
}
cout<<"Number of words : "<<count<<endl;
Run Code Online (Sandbox Code Playgroud)

此处输出为1,这是正确的.

什么行不通

ifstream in("CallHello.cpp");
while(in >> s && s == "cout") {
    count++;
}
cout<<"Number of words : "<<count<<endl;
Run Code Online (Sandbox Code Playgroud)

输出为0,对于上面的错误.

为什么在使用&&时添加另一个条件会产生错误的输出?

小智 6

第一个条件将继续循环,同时in拥有的东西穿上s,你使用第二个条件while(in >> s && s == "cout")只会工作,如果你第一次检索值s具有的字符串 "cout",然后它会运行块,因此,你的第一个值s不也是"cout"第一次,所以它永远不会循环.