#include <iostream> using namespace std; int main() { cout << "Hello world\n"; <-- 1 cout << "Hello world" << '\n'; <-- 2 cout << "Hello world" << '\n' << flush; <-- 3 cout << "Hello world" << endl; <-- 4 }
Line 1 prints the string "Hello world" followed by a newline character, '\n'. This is analogous to the C statement, fprintf(stdout, "Hello world\n"); thus cout is analogous to C's stdout, and cerr (not shown) is analogous to stderr. Line 2 is logically equivalent to line 1: it prints the string "Hello world," then it prints a newline character, '\n'. This shows how the << operator can be cascaded allowing multiple things to be printed with the same statement. This is analogous to the C construct fprintf(stdout, "%s%c", "Hello world", '\n'). Line 3 also prints "Hello world" followed by a newline, but then it flushes the output buffer, forcing the characters to be sent to the operating system. This is normally not necessary with cout, but when output is being sent to a file it can be important to flush the output buffers at certain times, such as just before abort() is intentionally called. In C, flushing an output buffer is accomplished by calling fflush(stdout). Note that flushing the I/O buffers too much can slow down the application. Line 4 is a shorthand version of line 3. The symbol endl prints a newline character, '\n', followed by a flush symbol. Because endl flushes the buffer, it shouldn't be used very often since it can slow down the application. |