Should I use printf in my C++ code?

2019-01-10 08:07发布

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)\n", x, y);

// To do the same thing as above using cout....
cout << "(" << x << "," << y << ")" << endl;

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?

19条回答
forever°为你锁心
2楼-- · 2019-01-10 08:34

Use whatever fits your needs and preferences. If you're comfortable with printf then by all means use it. If you're happier with iostreams stick to 'em. Mix and match as best fits your requirements. This is software, after all - there's better ways and worse ways, but seldom is there only ONE way.

Share and enjoy.

查看更多
在下西门庆
3楼-- · 2019-01-10 08:34

streams are preferred in cpp as they adhere to the object oriented paradigm of cpp, beside being type safe.

printf , on the other hand is more of a functional approach.

only reason for not using printf in cpp code that i can think of is not being object oriented.

its more of a personal choice.

查看更多
手持菜刀,她持情操
4楼-- · 2019-01-10 08:35

I do not like printf. Its lack of type-safety makes it dangerous to use, plus the need to remember format specifiers is a pain. The templated operators that smartly do the right thing are much better. So I always use the C++ streams in C++.

Granted, many people prefer printf, for other reasons, enumerated elsewhere.

查看更多
我欲成王,谁敢阻挡
5楼-- · 2019-01-10 08:35

I use printf because I hate the ugly <<cout<< syntax.

查看更多
The star\"
6楼-- · 2019-01-10 08:36

It depends on the situation. Nothing is perfect. I use both. Streams are good for custom types as you can overload the >> operator in ostream. But when it comes to spacing and etc it's better to use printf(). stringstream and like are better than the C style strcat(). So use one that's appropriate for the situation.

查看更多
啃猪蹄的小仙女
7楼-- · 2019-01-10 08:38

I have read warnings saying that cout and cerr are unsafe for multithreading. If true, this is a good reason to avoid using them. Note: I use GNU g++ with openMP.

查看更多
登录 后发表回答