sscanf("0X80.9", "%f", &value) 将值设置为十六进制浮点数而不是浮点数 [英] sscanf("0X80.9", "%f", &value) sets value to a hex float not a float

查看:180
本文介绍了sscanf("0X80.9", "%f", &value) 将值设置为十六进制浮点数而不是浮点数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一些读取字母值对的代码.可以简化为:

I have some code that reads letter value pairs. It can be simplified as:

float value = 0.0;
sscanf("0X80.9", "%f", &value);

在 Visual Studio 2013 中,值 = 0

In Visual Studio 2013, value = 0

在 Visual Studio 2015 及更高版本中,值 = 128.5625(即十六进制的 0x80 = 十进制的 128)

In Visual Studio 2015 and above, value = 128.5625 (i.e. 0x80 in hex = 128 in decimal)

有人知道为什么会改变吗?更重要的是,有人知道如何让它像以前一样工作吗?

Anyone know why this has changed? More importantly, anyone know how to make it work like it used to?

推荐答案

C99 添加了一个新特性,十六进制浮点常量.它还为 *scanf() 函数添加了新格式.(源代码中的十六进制浮点常量必须有指数部分;对于scanf,指数是可选的.)

C99 added a new feature, hexadecimal floating-point constants. It also added new formats to the *scanf() functions. (A hexadecimal floating-point constant in source code must have an exponent part; for scanf, the exponent is optional.)

scanf 尽可能多地读取与格式一致的输入.对于 1999 之前的 C,这是初始的 "0";剩下下面的"X80.9".对于 C99,"0X80.9" 有效,并转换为浮点值 128.5625.(格式与 strtof() 接受的格式相同.)

scanf reads as much of the input as it can that's consistent with the format. For pre-1999 C, this is the initial "0"; the following "X80.9"is left. For C99, "0X80.9" is valid, and is converted to the floating-point value 128.5625. (The format is the same as what's accepted by strtof().)

C++ 标准通过引用包含了大部分 C 标准库.直到 c++2012 才更新到 C99 版本的 C 库.

The C++ standard includes most of the C standard library by reference. It didn't update to the C99 version of the C library until c++2012.

很可能 Visual Studio 2015 支持 C++12 或更高版本,而 Visual Studio 2013 不支持.

Most likely Visual Studio 2015 supports C++12 or later, and Visual Studio 2013 doesn't.

由于新行为现在是标准的,我建议调整您的代码来处理它,而不是试图强制执行旧行为.如果有办法让 VS2015 以旧方式运行,则应记录在案.

Since the new behavior is now standard, I suggest adapting your code to deal with it rather than trying to force the old behavior. If there's a way to make VS2015 behave in the old way, it should be documented.

这篇关于sscanf("0X80.9", "%f", &value) 将值设置为十六进制浮点数而不是浮点数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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