Linux中的printf问题
以下是在 HP 和 HP 上打印格式化“1.2”的简单程序。 Linux。 然而,行为是不同的。 我不想让问题变得更大,但实际发生这种情况的程序在字符串中有一个浮点值,因此使用 %f 不是一个选项(即使使用 sprintf)。
以前有人遇到过这种情况吗?哪种行为是正确的?
这不应该是编译器问题,但仍然在 gcc、icpc、icc、g++ 上尝试过。
#include <stdio.h>
int main()
{
printf("%s = [%010s]\n", "[%010s]", "1.2");
return 0;
}
**HP:**
cc test2.c -o t ; ./t
[%010s] = [00000001.2]
**Linux:**
icc test2.c -o t ; ./t
[%010s] = [ 1.2]
编辑:非常感谢大家的回复:)
Following is a simple program to print formatted "1.2" on HP & Linux.
However, the behavior is different.
I do not want to make the question bigger but the program where this is actually occurring has a float value in a string, so using %f is not an option (even using sprintf).
Has anyone encountered this before? Which behavior is correct?
This should not be a compiler issue but still have tried it on gcc, icpc, icc, g++.
#include <stdio.h>
int main()
{
printf("%s = [%010s]\n", "[%010s]", "1.2");
return 0;
}
**HP:**
cc test2.c -o t ; ./t
[%010s] = [00000001.2]
**Linux:**
icc test2.c -o t ; ./t
[%010s] = [ 1.2]
Edit: Thank you all very much for the responses :)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
从 glibc
printf(3)
手册页来看:因此不能期望带有
s
的0
标志用0< 填充字符串/code>s 在基于 glibc 的系统上。
From the glibc
printf(3)
man page:So a
0
flag withs
cannot be expected to pad the string with0
s on glibc-based systems.根据
man
页面,0
标志对于 d、i、o、u、x、X、a、A、e、E 以外的任何内容的行为, f、F、g 和 G 转换未定义。所以两者都很好。编辑:当我说“很好”时,我的意思是从编译器/libc 的角度来看。从应用程序的角度来看,您所依赖的行为(在 Linux 和 HP 上)是一个错误,您应该正确执行格式化打印。
According to the
man
page, the behaviour of the0
flag for anything other than d, i, o, u, x, X, a, A, e, E, f, F, g, and G conversions is undefined. So both are fine.EDIT: When I say "fine", I mean from the compiler/libc standpoint. From your application's point of view, the behaviour you're relying on (on both Linux & HP) is a bug and you should do your formatted printing correctly.
如果您不需要前导零填充,请省略前导零填充指示符:
实现用零填充字符串有点令人惊讶,但它很容易纠正。
If you don't want leading zero fill, omit the leading zero fill indicator:
It is somewhat surprising that an implementation honors filling a string with zeros, but it is easily corrected.
根据
printf
的文档,添加 Ignacio Vazquez-Abrams 所说的内容,你所做的结果是未定义的行为。两个操作系统产生不同结果的事实并不意外。事实上,在 Ubuntu 上使用 gcc 4.5.2 编译代码会出现以下警告:
Adding to what Ignacio Vazquez-Abrams said, according to the documentation for
printf
, the result of what you are doing is undefined behavior. The fact that two OSes produce different results is not unexpected.In fact, compiling your code with gcc 4.5.2 on Ubuntu gives the following warning: