Quantcast
Channel: 'printf' vs. 'cout' in C++ - Stack Overflow
Viewing all articles
Browse latest Browse all 19

Answer by mishal153 for 'printf' vs. 'cout' in C++

$
0
0

For me, the real differences which would make me go for 'cout' rather than 'printf' are:

1) << operator can be overloaded for my classes.

2) Output stream for cout can be easily changed to a file :(: copy paste :)

#include <iostream>#include <fstream>using namespace std;int main (){    cout << "This is sent to prompt"<< endl;    ofstream file;    file.open ("test.txt");    streambuf* sbuf = cout.rdbuf();    cout.rdbuf(file.rdbuf());    cout << "This is sent to file"<< endl;    cout.rdbuf(sbuf);    cout << "This is also sent to prompt"<< endl;    return 0;}

3) I find cout more readable, especially when we have many parameters.

One problem with cout is the formatting options. Formatting the data (precision, justificaton, etc.) in printf is easier.


Viewing all articles
Browse latest Browse all 19

Trending Articles





<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>