We took a quick look at output in the previous lab; we'll expound on that just a bit.
Output in C++ is done with the cout object. This is the name
of the output screen or window. To actually send something to the
screen, C++ gives us the << operator. In general, an output
statement looks like this:
cout <<Value1<<Value2<< ... <<ValueN;
where each ValueI is replaced with objects. Note that
<< operators separate each of the values.
As mentioned in the introduction to the lab, output statements are actually output expressions. However, we need the semicolon to make it a statement which is what the compiler demands.
endl ObjectYou may have noticed a strange object in the output statements of our
programs: endl. In your output, you should notice that
endl stops the current line of output and starts the next
output on the next line. This suggests that endl is
interchangeable with "\n". But just how interchangeable?
Add this line of code in your program:
cout << "Line #1." << "\n" << "Line #2" << "\n";Don't both removing anything from your program since you'll need it later. Recompile and run your program.
Question #3.1.1: What does this statement print? Be very precise with the line breaks.
Replace each "\n" with an endl. Recompile and run
your program.
Question #3.1.2: How has the output changed?
endl is a variable for an object, apparently some type of
string object with a newline character in it. (It might have
other characters we can't see.) As we know, variables do not
magically appear in C++. Like cin and cout, the
object endl comes from the iostream library.
But that's a bit strange, right? Why not use "\n" all of
the time? We could make the output expression from above much
simpler:
cout << "Line #1.\nLine #2\n";So why bother with
endl? Actually, endl is more than
just the newline character; it also indicates that you want the
output to appear on the screen right now. Usually, for these
labs, you won't find this to be a big deal. It may never matter to
you (depending on your program, compiler, and operating system).
Play it safe and use endl at the end of a prompt, but
otherwise it doesn't really matter if you use endl or "\n".
We can nearly output anything. Our program currently prints strings, integer objects, and even the result of an expression. We can also print complex objects:
cout << cin << endl;Add this line to your program, recompile, and execute the program.
Question #3.1.3: What does this line print?
Printing the value of cin isn't really useful; the point is
that we can print it. For some objects we'll see later on,
this can be very useful, especially in debugging our code.