在 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
, andG
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/