Sams Teach Yourself C in 21 Days

(singke) #1
The C++ Programming Language 651

BD2


Printing in C++ ..............................................................................................


In your C listings, you used a number of functions to print such as puts()andprintf().
Although you can use these C functions in a C++ listing, you really should not.
Functions such as these are not object-oriented, nor are they as optimal as the C++ alter-
natives.
As you saw in Listing B2.2, when printing in a C++ program, you should use the cout
object. The coutobject enables you to send output to the standard output device. As
stated before, you do not use coutin the same way you use a function in C. Rather, you
redirect values to cout, and it, in turn, sends them to the standard output device.
One of the benefits of coutis that it is object-oriented. The coutobject encapsulates
printing functionality. When using printf(), you had to specify the data types of vari-
ables being printed. With the coutobject, you do not. It adapts to handle what you send
it. Listing B2.3 helps to illustrate this.

LISTINGB2.3 cout.cpp. Printing with cout
1: //Using cout with different data types
2: #include <iostream.h>
3:
4: int main(int argc, char* argv[])
5: {
6: int an_int = 123;
7: long a_long = 987654321;
8: float a_float = (float) 123.456;
9: char a_char = ‘A’;
10: char *a_string = “A String”;
11: bool a_boolean = true;
12:
13: cout << “\n”;
14: cout << “an int: “<< an_int << ‘\n’;
15: cout << “a long: “<< a_long << ‘\n’;
16: cout << “a float: “<< a_float << ‘\n’;
17: cout << “a char: “<< a_char << ‘\n’;
18: cout << “a string: “<< a_string << ‘\n’;
19: cout << “a bool: “<< a_boolean << ‘\n’;
20:
21: return 0;
22: }

Note Tomorrow, you will learn more about objects and classes.


37 448201x-Bonus2 8/13/02 11:18 AM Page 651

Free download pdf