C++ 如何打印 uint64_t?失败:“格式中的虚假尾随 '%'”
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/8132399/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to printf uint64_t? Fails with: "spurious trailing ‘%’ in format"
提问by Dan
I wrote a very simple test code of printf uint64_t:
我写了一个很简单的printf uint64_t测试代码:
#include <inttypes.h>
#include <stdio.h>
int main()
{
uint64_t ui64 = 90;
printf("test uint64_t : %" PRIu64 "\n", ui64);
return 0;
}
I use ubuntu 11.10 (64 bit) and gcc version 4.6.1 to compile it, but failed:
我使用 ubuntu 11.10(64 位)和 gcc 版本 4.6.1 来编译它,但失败了:
main.cpp: In function ‘int main()':
main.cpp:9:30: error: expected ‘)' before ‘PRIu64'
main.cpp:9:47: warning: spurious trailing ‘%' in format [-Wformat]
回答by Will
The ISO C99 standard specifies that these macros must only be defined if explicitly requested.
ISO C99 标准规定只有在明确要求时才必须定义这些宏。
#define __STDC_FORMAT_MACROS
#include <inttypes.h>
... now PRIu64 will work
回答by Anders Eliasson
When compiling memcached under Centos 5.x i got the same problem.
在 Centos 5.xi 下编译 memcached 时遇到了同样的问题。
The solution is to upgrade gcc and g++ to version 4.4 at least.
解决方案是至少将 gcc 和 g++ 升级到 4.4 版本。
Make sure your CC/CXX is set (exported) to right binaries before compiling.
确保在编译之前将 CC/CXX 设置(导出)为正确的二进制文件。
回答by vitaut
Since you've included the C++ tag, you could use the {fmt} libraryand avoid the PRIu64
macro and other printf
issues altogether:
由于您已经包含了 C++ 标记,您可以使用{fmt} 库并完全避免PRIu64
宏和其他printf
问题:
#include <fmt/core.h>
int main() {
uint64_t ui64 = 90;
fmt::print("test uint64_t : {}\n", ui64);
}
The formatting facility based on this library is proposed for standardization in C++20: P0645.
基于此库的格式化工具被提议用于 C++20 中的标准化:P0645。
Disclaimer: I'm the author of {fmt}.
免责声明:我是 {fmt} 的作者。