w 是指定输出宽度的参数,p 是数字,应该以八进制打印 这两个变量都应该是固定宽度的整数 (uint32_t)(这是我的编程课的任务)。 我用谷歌搜索,我可以使用宏 PRIo32 (inttypes.h) 以八进制打印 int32_t,但我找不到任何宽度说明符的宏。 所以当我尝试时:
printf("%*" PRIo32 "\n", w, p);
我在测试系统中遇到这个错误
error: field width specifier '*' expects argument of type 'int', but argument 2 has type 'int32_t' [-Werror=format=]
有没有宏可以解决这个问题?或者我应该尝试其他方法?
最佳答案
将 uint32_t
宽度转换为 int
。 @Kamil Cuk
// printf("%*" PRIo32 "\n", w, p);
printf("%*" PRIo32 "\n", (int) w, p);
如有必要,检测极端情况
assert(w <= INT_MAX);
printf("%*" PRIo32 "\n", (int) w, p);
不需要关于 int
范围的假设。
更深层次
请注意,由于环境限制,具有巨大宽度的单个打印会遇到麻烦。宽度超过 4095 左右可能根本不起作用。
Environmental limits The number of characters that can be produced by any single conversion shall be at least 4095. C17dr § 7.21.6.1 15
代码可以使用下面的代码来处理病态的大宽度——尽管它效率不高。
uint32_t w2 = w;
while (w2 > 100) {
w2--;
putchar(' ');
}
printf("%*" PRIo32 "\n", (int) w2, p);
关于c - 使用具有固定宽度整数类型变量的 printf 宽度说明符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58287366/