More Wonders of <I>cout</I>


Notice that we can send endl to cout, even though it isn't a string. Remember that cout can be given every standard type of data that there is in C++, be it a string, a number, a character, or the special cursor-movers (such as endl). For instance, look at this use of cout:

int a;
float b;

a = 4;
b = 52.2

cout << "Hey World, it's me. Again.";
cout << endl;
cout << "World, do you like the number ";
cout << a;
cout << " or ";
cout << b;
cout << " better?";
cout << endl;

Hopefully that was fairly easy to understand. However, please take a moment to go through it slowly; Although it may seem too easy to waste time on, cout is what you'll use more than anything else in C++, so don't short-change your knowledge of it to save a few minutes. To help you out, here's its output:

Hey World, it's me. Again.
World, do you like the number 4 or 52.2 better?

Here's the cool part -- you don't have to put each of those pieces of the second line in different statements! You can combine them all by simply using << between the pieces of data. Here's an example of this trick:

cout << "Hey World, it's me. Again." << endl;

Neat, huh? The way this works is that the C++ compiler runs this in two steps. First, it executes "cout << "Hey World, it's me. Again."", which you might find easier at this point to think of as a function in Pascal. Then, the statement returns the value of cout; this means that the entire block of "cout << "Hey World, it's me. Again."" turns into "cout", which of course means that the remaining line looks like "cout << endl", which is run just as if it had been on a different line. Using this feature of C++, let's reduce the program at the top of the page to a couple lines:

int a;
double b;

a = 4;
b = 52.2;

cout << "Hey World, it's me. Again." << endl;
cout << "World, do you like the number " << 4 << " or ";
cout << 52.2 << " better?" << endl;

See how much easier that is? We hope you'll recognize that it's kind of like Pascal's Write and Writeln's ability to list variables in-between text. One thing that's neat about the way C++ does it, though, is that you can put many carriage returns in a single statement. Take this line, for example:

cout << "World, what's up?" << endl << endl << endl << endl << endl << endl;


Table of Contents

Hello, World! | The Pre-Processor | Headers | cout: The Black Box
More Wonders of cout | cin: cout's evil twin | Exercises