FAQ 2.12 What are the basics of stream output?

graphics/new_icon.gif

C++ supports C-style output, such as the printf() family of functions. However it is often better to use the native C++ output services. With the native C++ output services, output is directed to an output stream object. For example, cout is an output stream object that is attached to the process's standard output device, often to the terminal from which the program is run. Syntactically these C++ output services look as if they're shifting things into the output stream object. The <iostream> header is needed when using these services:

 #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 } 

(1) Line 1

(2) Line 2

(3) Line 3

(4) Line 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.



C++ FAQs
C Programming FAQs: Frequently Asked Questions
ISBN: 0201845199
EAN: 2147483647
Year: 2005
Pages: 566
Authors: Steve Summit

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net