为什么stringstream>>更改故障目标值? [英] Why does stringstream >> change value of target on failure?

查看:222
本文介绍了为什么stringstream>>更改故障目标值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

从Stroustrup的TC ++ PL,第3版,第21.3.3节:

From Stroustrup's TC++PL, 3rd Edition, Section 21.3.3:


如果我们尝试读入变量v和操作失败,v的值应该保持不变(如果v是istream或ostream成员函数处理的类型之一,则不会改变)。

If we try to read into a variable v and the operation fails, the value of v should be unchanged (it is unchanged if v is one of the types handled by istream or ostream member functions).

以下示例似乎与上述报价相矛盾。基于上面的引用,我期望v的值保持不变 - 但它被归零。这个明显矛盾的行为的解释是什么?

The following example appears to contradict the above quote. Based on the above quote, I was expecting the value of v to remain unchanged -- but it gets zeroed. What's the explanation for this apparent contradictory behaviour?

#include <iostream>
#include <sstream>

int main( )
{
    std::stringstream  ss;

    ss  << "The quick brown fox.";

    int  v = 123;

    std::cout << "Before: " << v << "\n";

    if( ss >> v )
    {
        std::cout << "Strange -- was successful at reading a word into an int!\n";
    }

    std::cout << "After: " << v << "\n";

    if( ss.rdstate() & std::stringstream::eofbit  ) std::cout << "state: eofbit\n";
    if( ss.rdstate() & std::stringstream::failbit ) std::cout << "state: failbit\n";
    if( ss.rdstate() & std::stringstream::badbit  ) std::cout << "state: badbit\n";

    return 1;
}

输出我使用x86_64-w64-mingw32-g ++。exe(rubenvb -4.7.2-release)4.7.2 is:

The output I get using x86_64-w64-mingw32-g++.exe (rubenvb-4.7.2-release) 4.7.2 is:

Before: 123
After: 0
state: failbit

感谢。

推荐答案

此参考资料


如果提取失败(例如,如果一个字母输入到一个数字的预期位置),值保持未修改,并设置failbit(,直到C ++ 11

如果提取失败,则将零写入值,并设置failbit。如果提取导致值太大或太小而无法容纳值,那么将写入std :: numeric_limits :: max()或std :: numeric_limits :: min(),并设置failbit标志。 (自C ++ 11

If extraction fails, zero is written to value and failbit is set. If extraction results in the value too large or too small to fit in value, std::numeric_limits::max() or std::numeric_limits::min() is written and failbit flag is set. (since C++11)

似乎你的编译器是在C ++ 11模式,这改变了行为。

It seems that your compiler is compiling in C++11 mode, which changes the behavior.

输入操作符使用locale facet std :: num_get get 函数调用 do_get 。对于C ++ 11,指定使用 std :: strtoll 等。 et al。类型的函数。在C ++ 11之前,它显然使用了 std :: scanf 样式解析(通过引用,我没有访问C ++ 03规范)提取数字。行为的变化是由于解析输入的这种变化。

The input operator uses the locale facet std::num_get whose get function invokes do_get. For C++11 it's specified to use std::strtoll et. al. type of functions. Before C++11 it apparently used std::scanf style parsing (going by the reference, I don't have access to the C++03 specification) to extract the numbers. The change in behavior is due to this change in parsing the input.

这篇关于为什么stringstream&gt;&gt;更改故障目标值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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