c - 使用具有固定宽度整数类型变量的 printf 宽度说明符

标签 c printf posix int32

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/

相关文章:

c - 模拟 printf 堆栈弹出

c - 在 C 中打印格式化字符串

c - 系统调用是否直接发送到内核?

c - 使用线程,我应该如何处理理想情况下应该按顺序发生的事情?

关闭标准输入

c - 如何在使用 Diskpart 命令行实用程序隐藏驱动器后获得访问权限

c - 替代合并链表(C代码)

指向数组定义明确行为的 C 指针

c - C : Addition and Printing简介

c++ - 使用c++在当前运行的进程中获取X显示变量