std::endl vs. '\n' (C++)


Match word(s).

If you have any questions or comments,
please visit us on the Forums.

FAQ > What's the difference between... > std::endl vs. '\n' (C++)

This item was added on: 2003/02/19

When writing output in C++, you can use either std::endl or '\n' to produce a newline, but each has a different effect.

  • std::endl sends a newline character '\n' and flushes the output buffer.
  • '\n' sends the newline character, but does not flush the output buffer.

    The distinction is very important if you're writing debugging messages that you really need to see immediately, you should always use std::endl rather than '\n' to force the flush to take place immediately.

    The following is an example of how to use both versions, although you cannot see the flushing occuring in this example.

    
    #include <iostream> 
    
    int main(void)
    {
      std::cout <<"Testing 1" <<std::endl;
      std::cout <<"Testing 2\n";
    }
    
    /*
     * Program output:
     Testing 1
     Testing 2
    
     *
     */
    
    

    Credit: Eibro

  • Script provided by SmartCGIs