执行以下代码时出现一个错误
#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;
}
它打印出最后一个标记“you”两次,但是如果我进行以下更改,一切正常。
while(iss >> tokens){
cout << tokens << endl;
}
谁能解释一下 while 循环是如何运行的。谢谢
那是对的。条件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
正是出于这个原因,您应该始终使用您展示的第二种方法。在这种方法中,如果读取不成功,则不会进入循环。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)