VS2015 中 sprintf() 和 wsprintf() 的格式差异 [英] Formatting differences between sprintf() and wsprintf() in VS2015

查看:46
本文介绍了VS2015 中 sprintf() 和 wsprintf() 的格式差异的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在将一些代码从多字节转移到 unicode,发现我的字符串格式有误.看起来 Visual Studio 2015 在 sprintf() 和 wsprintf() 之间处理宽度参数说明符*"的方式不同.这是编译器错误还是副作用,还是我遗漏了一些非常明显的东西?

I am moving some code from multibyte to unicode, and finding my string formatting coming out wrong. It looks like Visual Studio 2015 handles the width argument specifier '*' differently between sprintf() and wsprintf(). Is this a compiler bug or side-effect, or am I missing something really obvious?

下面的代码,带输出:

char    cOutA [ 64 ];
wchar_t wcOutA [ 64 ];

sprintf ( cOutA, "Multibyte = %.*f\n", 3, 2.12345 );
wsprintf ( wcOutA, L"Unicode = %.*f\n", 3, 2.12345 );

printf ( cOutA );
wprintf ( wcOutA );

<小时>

输出:

Multibyte = 2.123
Unicode = *f

<小时>

我希望两者都能给我一个小数点后 3 位的浮点数.我做错了什么?


I was expecting both to give me a floating point number to 3 decimal places. What am I doing wrong?

推荐答案

正如 Hans 在评论中提到的,答案是永远不要使用 wsprintf().它总是被破坏,不支持与 C 标准swprintf()"相同的格式参数,并且 Microsoft 文档没有说明它是如何被破坏的或为什么会被破坏.

As mentioned by Hans in the comments, the answer is you should never use wsprintf(). It's always been broken, does not support the same formatting arguments as C standard "swprintf()" and the Microsoft documentation does not make clear how it is broken or why.

我只是在尝试调试相关函数时才发现这一点:wvsprintf().这个函数似乎有同样的限制,也应该用它的工作替代品来代替:vswprintf()".名称与工作版本的相似性非常令人遗憾,与标准 C 库函数和命名方法的明显相似性也是如此.我不知道为什么这些函数仍然在 2017 年交付,也不知道为什么 Microsoft 编译器在使用不受支持的参数时不会像sprintf()"那样生成警告.

I only discovered this when trying to debug a related function: wvsprintf(). This function seems to have the same limitations, and should also be replaced by its working replacement: "vswprintf()". The similarity of the names to the working versions is very unfortunate, as is the apparent closeness to standard C library functions and naming methodologies. I have no idea why these functions are still delivered in 2017, nor why the Microsoft compiler does not generate a warning when used with unsupported arguments in the same way it does for "sprintf()".

我发布此内容是为了提高知名度,因为在 Google 上搜索这些功能似乎并没有让这些巨大的缺陷显而易见.

I'm posting this for visibility as searching for these functions on Google doesn't seem to make these massive flaws obvious.

这篇关于VS2015 中 sprintf() 和 wsprintf() 的格式差异的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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