2.1. More Output¶
As I mentioned in the last chapter, you can put as many statements as
you want in
main. For example, to output more than one line:
This program prints two different statements on two different lines
As you can see, it is legal to put comments at the end of a line, as well as on a line by themselves.
The phrases that appear in quotation marks are called strings, because they are made up of a sequence (string) of letters.
In C++, strings are declared as type
string. We’ll explain what that
means in the next few pages.
Actually, strings can contain any combination of letters, numbers, punctuation marks, and other special characters.
Often it is useful to display the output from multiple output statements
all on one line. You can do this by leaving out the first
This program prints two different statements on the same line.
In this case the output appears on a single line as
world!. Notice in
main that there is a space between “Goodbye,” and the
second quotation mark. This space appears in the output, so it affects
the behavior of the program.
Spaces that appear outside of quotation marks generally do not affect the behavior of the program. For example, I could have written:
This program accomplishes the same thing as the one above. The difference is that there are no spaces separating the different components of each line. This is a matter of personal preference.
This program would compile and run just as well as the original. The breaks at the ends of lines (newlines) do not affect the program’s behavior either, so I could have written:
This program accomplishes the same thing as the two above, but it only uses one line. Once again, this is a matter of personal preference. However, this format is pretty messy and relatively hard to follow.
That would work, too, although you have probably noticed that the program is getting harder and harder to read. Newlines and spaces are useful for organizing your program visually, making it easier to read the program and locate syntax errors.
Construct a main function that prints “Snap!” on the first line, “Crackle!” on the third line, and “Pop!” on the sixth line. You might not use all of endl blocks provided.
Construct a main function that prints “Hello, world!” so that “Hello,” and “world!” are printed on two separate lines.