Stringstream c++ while loop

穿精又带淫゛_ 提交于 2020-05-13 13:37:08

问题


Program finds integeres between commas like "2,33,5" -> 2 33 5. The problem is why is it working if I put for example string like "0,12,4". shouldn't the stringstream put 0 into tmp so the loop was like while(0) at the beginning?

 vector<int> parseInts(string str) {
 stringstream ss(str);   //getting string 
 vector<int> result;
 char ch;
 int tmp;
 while(ss >> tmp) {      //while(IS IT INTEGER ALREADY OR NOT?)
     result.push_back(tmp);
     ss >> ch;           
}
return result;

回答1:


shouldn't the stringstream put 0 into tmp so the loop was like while(0) at the beginning?

The while condition is ss >> tmp. If you look at the documentation for cin, you will find that operator>>() returns a istream&. It does not return the input that you just read, in this case the int value 0.

In addition, istream (or one of it's base classes) overloads operator bool() which allows istream objects to be implicitly converted to a bool, the type required as the result of a while statements condition. An istream object will evaluate as false whenever an error occurs during the call to operator>>(). If there is no error, then it evaluates to true.

Since the input 0 is a valid int, the while loop continues the next iteration.



来源:https://stackoverflow.com/questions/47876920/stringstream-c-while-loop

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!