【问题标题】:using stringstream >> operator in if statement在 if 语句中使用 stringstream >> 运算符
【发布时间】:2013-02-10 23:50:54
【问题描述】:

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

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

【问题讨论】:

    标签: c++ stringstream


    【解决方案1】:

    stream 有一个 operator bool() 或 operator void*(),它返回(类似于)!fail() - 或者在 void * 失败时返回 NULL。所以,如果流没有失败,那很好。 operator &gt;&gt; 返回对 stream 对象的引用,因此编译器说“嗯,无法将流对象与真实值进行比较,让我们看看是否可以从中生成 bool 或 void *,是的我们可以,所以让我们使用它。

    【讨论】:

    • 是的!具体来说,它适用于std::basic_ios。请参阅此处的operator void* 和operator bool。 en.cppreference.com/w/cpp/io/basic_ios
    • 我假设第一个 cout 语句也是如此,因为它在整数提取失败时显示 0。编译器尝试将其设为 bool 或 void* 以便 cout 能够显示它。
    • 是的,至少会做类似的事情。
    【解决方案2】:

    答案在于converts std::ios to void*(替换为operator to convert basic_ios to a bool in C++11)的运算符:

    从 ios 派生的流对象可以转换为指针。如果设置了任一错误标志(failbit 或 badbit),则该指针为空指针,否则为非零指针。

    当您的流用于if、while 或for 条件时,将调用此运算符。对于需要编写的情况,还有一个一元 ! 运算符

    if (!(myStream >> num)) {
        ...
    }
    

    【讨论】:

    • +1,但应该注意,afaik,这是 C++11 之前的版本,即使几乎所有编译器仍然将其实现为 void*,即使在 C++11 模式下也是如此。对于严格的 C++11(要求 explicit operator bool()),Mats 的回答是正确的。
    猜你喜欢
    • 2013-04-30
    • 1970-01-01
    • 2017-03-06
    • 2013-03-19
    • 2011-05-15
    • 1970-01-01
    • 2012-12-28
    相关资源
    最近更新 更多