4

执行以下代码时出现一个错误

#include <iostream>
#include <sstream>
#include <string>

using namespace std;

int main (int argc, char* argv[]){
    string tokens,input;
    input = "how are you";
    istringstream iss (input , istringstream::in);
    while(iss){
        iss >> tokens;
        cout << tokens << endl;
    }
    return 0;

}

它两次打印出最后一个标记“你”,但是如果我进行以下更改,一切正常。

 while(iss >> tokens){
    cout << tokens << endl;
}

谁能解释一下while循环是如何运行的。谢谢

4

1 回答 1

9

那是对的。只有在您读到流的末尾之后,该条件while(iss)才会失败。因此,在您从流中提取之后,它仍然是正确的。"you"

while(iss) { // true, because the last extraction was successful

所以你尝试提取更多。此提取失败,但不影响存储在 中的值tokens,因此再次打印。

iss >> tokens; // end of stream, so this fails, but tokens sill contains
               // the value from the previous iteration of the loop
cout << tokens << endl; // previous value is printed again

出于这个原因,您应该始终使用您展示的第二种方法。在这种方法中,如果读取不成功,则不会进入循环。

于 2012-01-24T07:00:12.250 回答