“std::endl” vs “\n”

后端 未结 12 2421
耶瑟儿~
耶瑟儿~ 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:20

    The difference can be illustrated by the following:

    std::cout << std::endl;
    

    is equivalent to

    std::cout << '\n' << std::flush;
    

    So,

    • Use std::endl If you want to force an immediate flush to the output.
    • Use \n if you are worried about performance (which is probably not the case if you are using the << operator).

    I use \n on most lines.
    Then use std::endl at the end of a paragraph (but that is just a habit and not usually necessary).

    Contrary to other claims, the \n character is mapped to the correct platform end of line sequence only if the stream is going to a file (std::cin and std::cout being special but still files (or file-like)).

提交回复
热议问题