问题
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