简体   繁体   English

在C ++中使用printf

[英]Use of printf in C++

A search of the site for "printf vs cout" turned up a discussion of the difference between the two, but that isn't what I was looking for. 在该网站上搜索“ printf vs cout”,引起了对两者之间区别的讨论,但这不是我想要的。 Coming from Python, I'm a huge fan of the way printf employs string formatting and I'd rather avoid cout if possible. 来自Python,我非常喜欢printf采用字符串格式的方式,如果可能的话,我宁愿避免使用cout

Is it considered bad practice to ignore cout and use printf exclusively? 忽略cout并仅使用printf是否被视为不好的做法? What would be the implications of doing this? 这样做的含义是什么? What are some cases where using printf wouldn't be an option? 在某些情况下不能使用printf情况是什么?

1) You can only use printf for fundamental types, and for integers it is really only usable for the "native" types int , long int etc. Something like uint32_t requires rather awkward and cumbersome macros for portable printing. 1)您只可以使用printf为基本类型,并为整数真的是只可用于“本地”类型的intlong int像等东西uint32_t需要便携式打印颇为尴尬和麻烦宏。 User-defined types are not supported at all. 完全不支持用户定义的类型。

2) printf is not typesafe. 2) printf不是类型安全的。 That is, the correctness of your code depends on the value of the formatting string, and you cannot tell whether your program is well formed from static analysis alone. 也就是说,代码的正确性取决于格式化字符串的 ,并且您不能仅凭静态分析就无法确定程序是否格式正确。 This is the fundamental weakness of the C typesystem, which "proper" C++ avoids. 这是C类型系统的根本缺陷,C ++可以避免“适当”的缺陷。

That said, printf (or perhaps (v)snprintf , rather) is usually quite a bit faster than iostreams, so in a high-performance context (eg high-frequency logging) it is a very competitive alternative. 就是说, printf (或者也许是(v)snprintf )通常比iostream快很多,因此在高性能环境(例如高频日志记录)中,它是一种非常有竞争力的选择。 However, if you just have occasional output operations, you should prefer iostreams, or some other flexible, typesafe, idiomatic C++ method. 但是,如果您只是偶尔进行输出操作,则应该使用iostream或其他一些灵活的,类型安全的,惯用的C ++方法。 (And admittedly iostreams is probably one of the most terrible corners of C++.) (当然,iostreams可能是C ++最可怕的角落之一。)

Is it considered bad practice to ignore cout and use printf exclusively? 忽略cout并仅使用printf是否被视为不好的做法?

No, if you prefer to use printf , go ahead. 不,如果您更喜欢使用printf ,请继续。

What would be the implications of doing this? 这样做的含义是什么?

None. 没有。 The C++ way would be to use cout , because it's supposed to be simpler. C ++的方法是使用cout ,因为它应该更简单。

What are some cases where using printf wouldn't be an option? 在某些情况下不能使用printf的情况是什么?

I doubt you'll find such cases. 我怀疑您会发现这种情况。 If you do, people writing them are too subjective. 如果这样做的话,编写它们的人会太主观。

cout is type-safe. cout是类型安全的。 cout is an ostream and so it has the same interface as other ostream s - for instance you can provide new overloads for printing foo . cout是一个ostream ,因此它与其他ostream s具有相同的接口-例如,您可以提供新的重载来打印foo

printf has format strings which occasionally are better than cout 's method of formatting. printf格式字符串有时比cout的格式化方法更好。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM