问题描述
程序查找逗号之间的整数,例如"2,33,5"-> 2 33 5.问题是,如果我输入例如"0,12,4"之类的字符串,为什么它能正常工作.字符串流不应该将0放入tmp以便循环像开始时的while(0)吗?
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;
推荐答案
while条件为 ss>>tmp
.如果查看 cin
的文档,则会发现 operator>>()
返回 istream&
.它不会不返回您刚刚读取的输入,在本例中为 int
值 0
.
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
.
此外, istream
(或其基类之一)会重载 operator bool()
,从而允许将 istream
对象隐式转换为 bool
,这是 while
语句条件的结果所需的类型.每当在调用 operator>>()
的过程中发生错误时, istream
对象将被评估为 false
.如果没有错误,则评估为 true
.
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
.
由于输入的 0
是有效的 int
,因此 while
循环将继续下一次迭代.
Since the input 0
is a valid int
, the while
loop continues the next iteration.
这篇关于Stringstream C ++ While循环的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!