[英]How to print uint32_t variables value via wprintf function?
It is a well-known fact that to print values of variables that type is one of fixed width integer types (like uint32_t
) you need to include cinttypes
(in C++) or inttypes.h
(in C) header file and to use format specifiers macros like PRIu32
. 一个众所周知的事实是,要打印类型为固定宽度整数类型之一(例如
uint32_t
)的变量的值,您需要包括cinttypes
(在C ++中)或inttypes.h
(在C中)头文件并使用格式说明符像PRIu32
这样的宏。 But how to do the same thing when wprintf
function is used? 但是使用
wprintf
函数时该怎么做? Such macro should expand as a string literal with L
prefix in that case. 在这种情况下,此类宏应扩展为带有
L
前缀的字符串文字。
If this will work or not actually depends on which standard of C the compiler is using. 是否可行,实际上取决于编译器使用的C标准。
From this string literal reference 从此字符串文字参考
Only two narrow or two wide string literals may be concatenated.
只能连接两个窄或两个宽字符串文字。 ( until C99 )
( 直到C99为止 )
and 和
If one literal is unprefixed, the resulting string literal has the width/encoding specified by the prefixed literal.
如果一个文字没有前缀,则生成的字符串文字具有由前缀文字指定的宽度/编码。 If the two string literals have different encoding prefixes, concatenation is implementation-defined.
如果两个字符串文字具有不同的编码前缀,则串联是实现定义的。 ( since C99 )
( 自C99以来 )
[Emphasis mine] [强调我的]
So if you're using an old compiler or one that doesn't support the C99 standard (or later) it's not possible. 因此,如果您使用的是旧的编译器或不支持C99标准(或更高版本)的编译器,则不可能。 Besides fixed-width integer types was standardized in C99 so the macros don't really exist for such old compilers, making the issue moot.
除了固定宽度整数类型是在C99中标准化的,因此对于这些旧的编译器而言,宏实际上并不存在,这引起了问题。
For more modern compilers which support C99 and later, it's a non-issue since the string-literal concatenation will work and the compiler will turn the non-prefixed string into a wide-character string, so doing eg 对于支持C99和更高版本的更现代的编译器,这不是问题,因为字符串文字级联将起作用,并且编译器会将非前缀的字符串转换为宽字符字符串,因此例如
wprintf(L"Value = %" PRIu32 "\n", uint32_t_value);
will work fine. 会很好的工作。
If you have a pre-C99 compiler, but still have the macros and fixed-width integer types, you can use function-like macros to prepend the L
prefix to the string literals. 如果您使用的是C99之前的编译器,但仍具有宏和固定宽度的整数类型,则可以使用类似函数的宏在字符串文字前加上
L
前缀。 Something like 就像是
#define LL(s) L ## s
#define L(s) LL(s)
...
wprintf(L"Value = %" L(PRIu32) L"\n", uint32_t_value);
Not sure where the problem is, but here (VS 2015) both 不确定问题出在哪里,但是在这里(VS 2015)
wprintf(L"AA %" PRIu32 L" BB", 123);
and 和
printf("AA %" PRIu32 " BB", 123);
compile correctly and give following output: 正确编译并提供以下输出:
AA 123 BB
A (weaker) alternative to using the macros from <inttypes.h>
is to convert/cast the the fixed width type to an equivalent or larger standard type. 使用
<inttypes.h>
的宏的一种(较弱)替代方法是将固定宽度类型转换/转换为等效或更大的标准类型。
wprintf(L"%lu\n", 0ul + some_uint32_t_value);
// or
wprintf(L"%lu\n", (unsigned long) some_uint32_t_value);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.