What is the difference between printf() and cout in C++?
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
#include
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.