c - Linux : printing a zero-padded string of specified length

标签 c format-specifiers

在 Linux 上,我正在使用 GNU gcc 4.9.2 版本,并在尝试打印指定长度的零填充字符串时出现奇怪的意外行为。这是我正在尝试的代码片段:

#include <cstdio>
#include <cstring>
int main()
{
  char buff[5];
  sprintf(buff,"%04s","12");
  printf("%s\n", buff);
  return 0;
}

虽然 http://www.cplusplus.com/reference/cstdio/printf/ 中给出的文档明确指出,在指定填充时,标志用零 (0) 而不是空格向左填充数字。 但是,它的打印空间填充了“12”,即“12”而不是“0012”。 补救措施?

最佳答案

manpage of printf你会发现一个确切的描述:

0

The value should be zero padded. For d, i, o, u, x, X, a, A, e, E, f, F, g, and G conversions, the converted value is padded on the left with zeros rather than blanks. [...] For other conversions, the behavior is undefined.

因此它不是为字符串定义的。一个实现可以用 0 填充,但不是必须的。这是未定义的行为。

以下解决方案使用 %.*s 语法作为格式说明符,因此无需使用 for 循环或多次 printf 调用。

char buff[5];
char str[] = "12";
size_t len = strlen(str);
sprintf(buff, "%.*s%s", len >= 4 ? 0 : (int)(4 - len), "0000", str);

此外,您应该考虑使用 snprintf 来防止缓冲区溢出。

snprintf(buff, sizeof(buff), "%.*s%s", len >= 4 ? 0 : (int)(4 - len), "0000", str);

snprintf 的格式化输出可能因不同的编译器而有所不同。在 Linux gcc 下,它总是附加一个尾随空字节 '\0'。 Visual Studio 2010 编译器无法确保要写入的字符串是否大于或等于缓冲区。

关于c - Linux : printing a zero-padded string of specified length,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45214773/

相关文章:

c++ - 函数名称别名

c - 通过 `printf` 中的格式说明符传递空字节

objective-c - 为什么 C 和 Objective-C 都没有 bool 值的格式说明符?

c - 如何使用 MPLAB X IDE 在库项目中创建全局变量

c - 如何将带有可变参数的函数声明为 stdcall?

c++ - 更改 MSVC 中可执行文件的启动目录

c - %zd 说明符是 C11 中的可选功能吗?

c - 添加两个整数变量并显示输出 C

c - C 中的格式说明符及其作用?

c - 在 C 中写入 char* 数组会引发段错误