为什么stringstream>>更改故障目标值?

编程入门 行业动态 更新时间:2024-10-25 10:33:50
本文介绍了为什么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;更改故障目标值?

本文发布于:2023-11-30 12:01:07,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1649875.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:目标值   故障   stringstream   amp   gt

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!