Stringstream C ++ While循环 [英] Stringstream c++ while loop

查看:123
本文介绍了Stringstream C ++ While循环的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

程序查找逗号之间的整数,例如"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;

推荐答案

stringstream 不应该将 0 放入 tmp 中,这样循环就像开始时的 while(0) 一样吗?

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

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循环的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆