C++ Primer For Java Programmers


Standard IO

<< The Standard Library | Table of Contents | Logical Constructs >>
Most command-line programs deal with input and output using either standard I/O or files. In this section, we explore both the C and C++ approaches to standard I/O.

C Standard Output

C provides the printf() function for printing formatted text to standard output. If you are familiar with the sys.out.printf() method in Java, then you should have no problem working with the C's printf() function since the method in Java is based on this C function.

Standard Output. Consider the following example

(:source lang=cpp:)
double subTotal;
double total;
double salesTax;
        :
printf( "Sales Report:\n" );
printf( "SubTotal:  %8.2f\n", subTotal );
printf( "Sales Tax: %8.2f\n", salesTax );
printf( "Total Due: %8.2f\n", total );

There is no separate C function for printing a newline after the text is printed. To produce a newline, you must include the '\n' character within the format string.

Format Specifiers. The printf() function has the following sytnax

printf( format-string [, value arguments ] )

The format-string consists of text and/or format specifiers. Any text within the string is printed verbatim, while format specifiers are replaced by values given as additional arguments.

(:note warn:) No error checking is performed by the printf() function. Thus, it is up to you to make sure you provide the appropriate number and type of values for the format specifiers given in the format-string. (:noteend:)

All of the format specifiers have an optional integer width value following the % and preceding the format code. The value is left-justified if the width value is negative and right-justified if it is positive. Format specifiers for real values also have an optional fractional-part width value which is appended to the width value and separated by a decimal point. For example

(:source lang=cpp:)
printf( "%d  %5d\n", value1, value2 );
printf( "%8f  %6.3f  %07.2f\n", avg1, avg2, avg3 );

The following table outlines the more common format specifiers that can be used with the printf() function.

Format Code Description
c
d
Ld
e
E
f
Lf
s
x
X

C Standard Input

C++ Standard I/O


<< The Standard Library | Table of Contents | Logical Constructs >>

Print - Changes - Search
Last modified: April 28, 2007, at 11:33 PM.