Formatted and unformatted output capabilities are provided by ostream
. Capabilities include output of standard data types with the stream insertion operator (<<
); output of characters via the put
member function; unformatted output via the write
member function; output of integers in decimal, octal and hexadecimal formats; output of floating-point values with various precision, with forced decimal points, in scientific notation (e.g., 1.234567e-03
) and in fixed notation (e.g., 0.00123457
); output of data justified in fields of designated widths; output of data in fields padded with specified characters; and output of uppercase letters in scientific notation and hexadecimal notation. We’ll demonstrate all of these capabilities in this chapter.
char*
VariablesC++ determines data types automatically—an improvement over C, but this feature sometimes “gets in the way.” For example, suppose we want to print the address stored in a char*
pointer. The <<
operator has been overloaded to output a char*
as a null-terminated C-style string. To output the address, you can cast the char*
to a void*
(this can be done to any pointer variable). Figure 13.1 demonstrates printing a char*
variable in both string and address formats. The address prints here as a hexadecimal (base-16) number—in general, the way addresses print is implementation dependent. To learn more about hexadecimal numbers, see Appendix D, Number Systems. We say more about controlling the bases of numbers in Section 13.6.1 and Section 13.7.4.
put
The basic_ostream
member function put
outputs one character at a time. For example, the statement
cout.put('A');
displays a single character A
. Calls to put
may be cascaded, as in the statement
cout.put('A').put('
');
which outputs the letter A
followed by a newline character. As with <<
, the preceding statement executes in this manner, because the dot operator (.
) associates from left to right, and the put
member function returns a reference to the ostream
object (cout
) that received the put
call. The put
function also may be called with a numeric expression that represents an ASCII value, as in the following statement, which also outputs A
:
cout.put(65);