在C++中使用istringstream时"关闭一个错误"

shi*_*raz 4 c++ istringstream

执行以下代码时,我遇到一个错误

#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;

}
Run Code Online (Sandbox Code Playgroud)

它打印出最后一个标记"你"两次,但是如果我做了以下更改,一切正常.

 while(iss >> tokens){
    cout << tokens << endl;
}
Run Code Online (Sandbox Code Playgroud)

任何人都可以解释我是如何运行while循环的.谢谢

Bjö*_*lex 9

那是正确的.while(iss)只有在读过流结束后,条件才会失败.因此,"you"从流中提取后,它仍然是真的.

while(iss) { // true, because the last extraction was successful
Run Code Online (Sandbox Code Playgroud)

所以你试着提取更多.此提取失败,但不会影响存储的值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
Run Code Online (Sandbox Code Playgroud)

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