'printf' vs. 'cout' in C++

后端 未结 16 1556
梦如初夏
梦如初夏 2020-11-22 07:04

What is the difference between printf() and cout in C++?

16条回答
  •  终归单人心
    2020-11-22 07:25

    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.

提交回复
热议问题