Sams Teach Yourself C++ in 21 Days

(singke) #1
Working with Streams 613

17


Outputting with cout..........................................................................................


You have used coutalong with the overloaded insertion operator (<<) to write strings,
integers, and other numeric data to the screen. It is also possible to format the data,
aligning columns and writing numeric data in decimal and hexadecimal. This section
shows you how.

Flushing the Output ........................................................................................


You’ve already seen that using endlwrites a newline and then flushes the output buffer.
endlcalls cout’s member function flush(), which writes all the data it is buffering. You
can also call the flush()method directly, either by calling the flush()member method
or by writing the following:
cout << flush();
This can be convenient when you need to ensure that the output buffer is emptied and
that the contents are written to the screen.

Functions for Doing Output ..........................................................................


Just as the extraction operator can be supplemented with get()and getline(), the inser-
tion operator can be supplemented with put()and write().

Writing Characters with put()
The function put()is used to write a single character to the output device. Because
put()returns an ostreamreference and because coutis an ostreamobject, you can con-
catenate put()the same as you can stack the insertion operator. Listing 17.10 illustrates
this idea.

LISTING17.10 Using put()


0: // Listing 17.10 - Using put()
1:
2: #include <iostream>
3:
4: int main()
5: {
6: std::cout.put(‘H’).put(‘e’).put(‘l’).put(‘l’).put(‘o’).put(‘\n’);
7: return 0;
8: }

Hello
OUTPUT
Free download pdf