我应该在我的 C++ 代码中使用 printf 吗?
我一般使用 cout
和 cerr
将文本写入控制台.但是有时我发现使用旧的 printf
语句更容易.当我需要格式化输出时使用它.
I generally use cout
and cerr
to write text to the console. However sometimes I find it easier to use the good old printf
statement. I use it when I need to format the output.
我会使用它的一个例子是:
One example of where I would use this is:
// Lets assume that I'm printing coordinates...
printf("(%d,%d)
", x, y);
// To do the same thing as above using cout....
cout << "(" << x << "," << y << ")" << endl;
我知道我可以使用 cout
格式化输出,但我已经知道如何使用 printf
.我有什么理由不应该使用 printf
语句?
I know I can format output using cout
but I already know how to use the printf
. Is there any reason I shouldn't use the printf
statement?
推荐答案
我的学生,先学cin
和cout
,再学printf
后来,绝大多数人更喜欢 printf
(或更常见的是 fprintf
).我自己发现 printf
模型具有足够的可读性,因此我已将其移植到其他编程语言中.Olivier Danvy 也是如此,他甚至使它成为类型安全的.
My students, who learn cin
and cout
first, then learn printf
later, overwhelmingly prefer printf
(or more usually fprintf
). I myself have found the printf
model sufficiently readable that I have ported it to other programming languages. So has Olivier Danvy, who has even made it type-safe.
如果您有一个能够对 printf
调用进行类型检查的编译器,我认为没有理由不在 C++ 中使用 fprintf
和朋友.
Provided you have a compiler that is capable of type-checking calls to printf
, I see no reason not to use fprintf
and friends in C++.
免责声明:我是一个糟糕的 C++ 程序员.
Disclaimer: I am a terrible C++ programmer.
相关文章