我通常使用cout和cerr写文本到控制台.然而,有时我发现使用旧的printf陈述更容易.我需要格式化输出时使用它.
我将使用它的一个例子是:
// Lets assume that I'm printing coordinates...
printf("(%d,%d)\n", x, y);
// To do the same thing as above using cout....
cout << "(" << x << "," << y << ")" << endl;
Run Code Online (Sandbox Code Playgroud)
我知道我可以使用格式化输出,cout但我已经知道如何使用printf.有什么理由我不应该使用这个printf陈述吗?
我正在尝试打印uint16_t和uint32_t值,但它没有提供所需的输出.
#include <stdio.h>
#include <netinet/in.h>
int main()
{
uint32_t a=12,a1;
uint16_t b=1,b1;
a1=htonl(a);
printf("%d---------%d",a1);
b1=htons(b);
printf("\n%d-----%d",b,b1);
return 0;
}
Run Code Online (Sandbox Code Playgroud)
我也用过
printf("%"PRIu32, a);
Run Code Online (Sandbox Code Playgroud)
这显示错误.
如何打印这些值以及所需的输出?
在研究如何printf()在C中执行跨平台格式字符串时(也就是说,考虑到我希望每个整数参数printf()应该是的位数),我在维基百科文章的这一部分中进行了讨论printf().本文讨论了可以传递给printf()格式化字符串的非标准选项,例如(似乎是特定于Microsoft的扩展):
printf("%I32d\n", my32bitInt);
Run Code Online (Sandbox Code Playgroud)
它接着说:
ISO C99包括inttypes.h头文件,其中包含许多用于独立于平台的printf编码的宏.
...然后列出一组可在所述标题中找到的宏.查看头文件,使用它们我必须写:
printf("%"PRId32"\n", my32bitInt);
Run Code Online (Sandbox Code Playgroud)
我的问题是:我错过了什么吗?这真的是标准的C99方式吗?如果是这样,为什么?(虽然我从未见过以这种方式使用格式字符串的代码并不感到惊讶,因为它看起来很麻烦......)
我正在编写奥林匹克运动会的各种节目,并试图提高时间效率.我正在寻找最快的输入方式,使用没有任何外部库的gcc编译器.
我之前使用过cin和cout,但发现scanf和printf要快得多.还有更快的方法吗?我不太关心空间复杂性,我宁愿选择更好的时间.
我有 uint8_t orig[ETH_ALEN];
我该如何使用它进行打印 __printf(3, 4)
被定义为 #define __printf(a, b) __attribute__((format(printf, a, b)))
Orig应该是以太网硬件地址.
c ×3
c++ ×2
c99 ×1
debugging ×1
formatting ×1
gcc ×1
performance ×1
printf ×1
time ×1
types ×1