“std::endl” vs “\n”

后端 未结 12 2373
耶瑟儿~
耶瑟儿~ 2020-11-21 04:35

Many C++ books contain example code like this...

std::cout << \"Test line\" << std::endl;

...so I\'ve always done that too. But

相关标签:
12条回答
  • 2020-11-21 05:13

    The std::endl manipulator is equivalent to '\n'. But std::endl always flushes the stream.

    std::cout << "Test line" << std::endl; // with flush
    std::cout << "Test line\n"; // no flush
    
    0 讨论(0)
  • 2020-11-21 05:14

    There's another function call implied in there if you're going to use std::endl

    a) std::cout << "Hello\n";
    b) std::cout << "Hello" << std::endl;
    

    a) calls operator << once.
    b) calls operator << twice.

    0 讨论(0)
  • 2020-11-21 05:14

    They will both write the appropriate end-of-line character(s). In addition to that endl will cause the buffer to be committed. You usually don't want to use endl when doing file I/O because the unnecessary commits can impact performance.

    0 讨论(0)
  • 2020-11-21 05:15

    If you use Qt and endl, you could accidentally end up using an incorrect endl which gives you very surprising results. See the following code snippet:

    #include <iostream>
    #include <QtCore/QtCore> 
    #include <QtGui/QtGui>
    
    // notice that there is no "using namespace std;"
    int main(int argc, char** argv)
    {
        QApplication qapp(argc,argv);
        QMainWindow mw;
        mw.show();
        std::cout << "Finished Execution!" << endl;
        // This prints something similar to: "Finished Execution!67006AB4"
        return qapp.exec();
    }
    

    Note that I wrote endl instead of std::endl (which would have been correct) and apparently there is a endl function defined in qtextstream.h (which is part of QtCore).

    Using "\n" instead of endl completely sidesteps any potential namespace issues. This is also a good example why putting symbols into the global namespace (like Qt does by default) is a bad idea.

    0 讨论(0)
  • 2020-11-21 05:18

    There might be performance issues, std::endl forces a flush of the output stream.

    0 讨论(0)
  • 2020-11-21 05:20

    The varying line-ending characters don't matter, assuming the file is open in text mode, which is what you get unless you ask for binary. The compiled program will write out the correct thing for the system compiled for.

    The only difference is that std::endl flushes the output buffer, and '\n' doesn't. If you don't want the buffer flushed frequently, use '\n'. If you do (for example, if you want to get all the output, and the program is unstable), use std::endl.

    0 讨论(0)
提交回复
热议问题