失败时C ++中的istream行为更改 [英] istream behavior change in C++ upon failure

查看:104
本文介绍了失败时C ++中的istream行为更改的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

取自: cppreference



直到C ++ 11:


如果提取失败(例如,如果输入一个字母, ),值保持不变,并设置failbit。


由于C ++ 11:


如果提取失败,则将零写入值,并设置failbit。如果提取导致值太大或太小以适合值,则 std :: numeric_limits< T> :: max() std: :numeric_limits< T> :: min(),并设置failbit标志。


这意味着以下片段:

  int x = 1; 
std :: cin>> X;
return x;

如果数值转换失败,将返回 1 之前的C ++ 11和 0 否则。



微妙的破碎变化?或者,在C ++ 11之前可能有什么样的代码可以保证这个变化?

解决方案

,在一些情况下(即严格地说不可能存在), operator>>
这是修复。



在2011年初的草案中,标准在这方面与2003年基本相同。在由Matt Austern(1998年)打开的库缺陷报告中, num_get<> :: get() / code>和 int
因此改为使用 long 版本,并检查读取的数字是否在正确的范围内。



缺陷报告是此处。 / p>

(没有真正解释为什么他们不认为他们可以保持原来预期的行为,但这是为什么标准的这一部分改变了。)


Take from: cppreference

Until C++11:

If extraction fails (e.g. if a letter was entered where a digit is expected), value is left unmodified and failbit is set.

Since 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<T>::max() or std::numeric_limits<T>::min() is written and failbit flag is set.

Due to this change, this means that the following snippet:

int x = 1;
std::cin >> x;
return x;

in the event that the numerical conversion fails, will return 1 before C++11, and 0 otherwise.

Why would the standard committee introduce such a subtle breaking change? Or rather, what kind of code was possible prior to C++11 that warranted this change?

解决方案

It seems as originally specified, the operator>>s were broken in some cases (i.e. strictly speaking couldn't exist). This is the "fix".

In a draft from early 2011, The Standard is basically the same in this regard as it was in 2003. However, in a library defect report opened by Matt Austern (in 1998!), num_get<>::get() doesn't exist for short and int. So they were changed to use the long version, and check the read number falls within the correct range.

The defect report is here.

(Doesn't really explain why they didn't think they could keep the originally intended behaviour, but it is why this part of The Standard was changed.)

这篇关于失败时C ++中的istream行为更改的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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