“std::endl” vs “\n”

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

    With reference This is an output-only I/O manipulator.

    std::endl Inserts a newline character into the output sequence os and flushes it as if by calling os.put(os.widen('\n')) followed by os.flush().

    When to use:

    This manipulator may be used to produce a line of output immediately,

    e.g.

    when displaying output from a long-running process, logging activity of multiple threads or logging activity of a program that may crash unexpectedly.

    Also

    An explicit flush of std::cout is also necessary before a call to std::system, if the spawned process performs any screen I/O. In most other usual interactive I/O scenarios, std::endl is redundant when used with std::cout because any input from std::cin, output to std::cerr, or program termination forces a call to std::cout.flush(). Use of std::endl in place of '\n', encouraged by some sources, may significantly degrade output performance.

提交回复
热议问题