使用stringstream>>if语句中的运算符 [英] using stringstream >> operator in if statement

查看:71
本文介绍了使用stringstream>>if语句中的运算符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

以下代码段旨在尝试使用stringstream对象从字符串中提取整数,并检测整数提取是否成功.stringstream类继承>>运算符,以返回对istream实例的引用.失败的整数提取如何导致myStream的str成员仍为strInput时等于0?

The following code snippet is meant to try and extract an integer from a string using a stringstream object and detect whether integer extraction was successful or not. The stringstream class inherits the >> operator to return a reference to an istream instance. How does failed integer extraction lead to myStream being equal to 0 while its str member is still strInput?

stringstream myStream(strInput);
if (myStream >> num){//successfull integer extraction}
else{//unsuccessfull integer extraction
cout<<myStream<<endl;
cout<<myStream.str().c_str()<<endl;}

推荐答案

stream ,它会返回(类似)!fail()-或在 void * 失败时返回NULL的情况.因此,如果流没有失败,那就很好. operator>> 返回对 stream 对象的引用,因此编译器说嗯,不能将流对象与真值进行比较,让我们看看是否可以用它做一个 bool void * ,是的,我们可以使用它.

There is an operator bool() or operator void*() for stream, which returns (something like) !fail() - or in case of void * a NULL when it failed. So, if the stream hasn't failed, it's fine. The operator >> returns a reference to the stream object, so the compiler says "Hmm, can't compare a stream object to truth, let's see if we can make a bool, or void * from it, yes we can, so let's use that.

这篇关于使用stringstream&gt;&gt;if语句中的运算符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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