Sunday 2 September 2012

Difference between '\n' and endl

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)
    {
      cout <<"Testing 1" <<endl;
      cout <<"Testing 2\n";
    }
    
    /*
     * Program output:
     Testing 1
     Testing 2
    
     *
     */
    
    
  • 1 comment: