Video Coming Soon...
05: Printing to the Screen
We can now get back to writing C++ code. From now on, when you create a new .cpp
file you should add it to your meson.build
file to build it. I'll show you how one more time in this exercise, but after this just assume that's what you need to do. If you need to do something special for an exercise I'll let you know.
In Exercise 02 you did some printing already when you wrote this line of code:
cout << "We'll have cake, in the end." << endl;
In this exercise we'll learn more about printing text in C++ and also a few other things:
- Escape codes to add special formatting to your output.
- How
use namespace std
isn't needed, but is convenient. - How to print to multiple output modes.
The Exercise Setup
Enter this code into a file named ex05.cpp
to get started:
#include <iostream>
int main() {
return 0;
}
This code does nothing but lays out the basic structure of a C++ program to get you started. You can then add this ex05.cpp
file to your meson.build
like this:
project('learn-cpp-the-hard-way', 'cpp',
default_options: ['cpp_std=c++20'])
executable('ex02', 'ex02.cpp')
executable('ex05', 'ex05.cpp')
The important line is at the end, which tells meson
to compile the ex05.cpp
file into the ./builddir/ex05
executable (./builddir/ex05.exe
on Windows). Once that's working, run your compile command:
meson compile -C builddir
This will make a ./builddir/ex05
executable but it will do nothing when you try to run it. This is on purpose since you'll then fill in the rest after you have this starter .cpp
file building.
NOTE: You could keep this "starter file" around for your future projects to get started quicker by copying it to
template.cpp
and then making a copy any time you start a new project. However, there is some advantage to typing this in each time until you feel you've memorized it. I'll leave this up to you.
With that you are ready to enter in the code for this exercise. This should be your process for each exercise going forward. Make a starter .cpp
for the exercise, add it to your meson.build
, and get it to compile. After that you can keep working and compiling until the exercise works.
The Code
Once you have your empty starter ex05.cpp
file working you should enter this code in and get it working:
View Source file ex05.cpp Only
#include <iostream>
int main() {
std::cout << "This is printed.\n";
std::cerr << "This writes to the error output.\n";
// notice the \t at the start
std::cout << "\tThis is tabbed in.\n";
return 0;
}
Remember you should enter this "one line at a time" or really "one thing at a time." I say "one thing" because many times you can enter one line, but sometimes you need to enter a few lines to make the code still build. You'll learn how much is needed as you learn to write C++ code.
Never Type in All The Code
The most important idea to take away from this process is that you never type all the code in and then try to make it work. This will end in disaster, and it's not how I or any professional programmer really works. If you find that you typed all the code in, then delete it and do it again. It may sound insane to make you do that, but trust me, you'll do a better job the second time and get more practice. If you try to make your "one shot" attempt work you'll be frustrated trying to find all the errors in the vast ocean of code you've written.
Introducing namespace
There actually is only one new thing in this code, which is the std::cout
syntax. If you remember in Exercise 02 you wrote this line of code at the start:
use namespace std;
This tells the compiler to search inside the std
namespace whenever you attempt to use something. A "namespace" is a collection of related C++ components under a common name. This allows programmers from different places to share their code without clashing. I could write a library that has a component named cout
and if I place it in a namespace
named zedscoolgear
then it won't conflict with the C++ namespace std
.
This means, in ex02.cpp
you told the compiler to lookup cout
automatically in the namespace std
. In the ex05.cpp
code you do not do this, so now you have to manually tell c++
where to find cout
. The cout
component lives inside std
, so you write std::cout
to say "look inside std
to find cout
and use it."
If this seems confusing right now, just keep in mind that it'll come up often enough going forward that you'll have plenty of opportunities to experience it and learn this concept. For now just know when you see x::y
it means get y from x
or find the y inside x
.
More on Strings
I've mentioned strings a few times but I haven't clearly defined what they are in C++. If you want to display or store text then you will use a string to store it. A string in C++ is written with "
(double-quote) characters like this:
"I am a string."
C++ will recognize you want to make a string when it encounters the first "
(double-quote), then it will gather up each character until it reaches the "
at the end. Once it does, it stores I am a string.
in the computer's memory but not the "
characters. Those are considered C++ code.
Once you've created a string you can alter it, store it in files, send it over a network, hand it to a C++ library, convert it to other formats, and many more things.
Escape Codes
Many times when you create a string you'll want to add characters that you can't actually write in the code. For example, if you need to add a newline or a TAB to indent the output. C++ has something called "escape codes" which allow you to insert special characters into your strings. Each escape code starts with a \
(back-slash) character and has one or more characters after it to indicate which special character to write.
Here's a table of most of the escape codes you'll mostly use in programming. Many of these are found in other languages, so learning them is very useful.
Escape | Name |
---|---|
\n | newline |
\t | tab |
More | to come |
Code Breakdown
Now that you understand more about namespaces, the ::
operator, and strings, we can break down the code line by line:
- 1
- This includes the
iostream
header that gives youstd::cout
andstd::err
. - 3
- Your usual entry point to your program at
int main()
. - 4
- The first output you use
std::cout
to send the string"This is printed."
to "c out" which is C++'s way of saying standard output. At the end of this is the escape code\n
which tells C++ to add a newline to the output. - 5
- The next output is to
std::cerr
which sends the string"This writes to the error output."
to "standard error." On many systems you have one output that's for normal data, and another output that's for errors. This line of code outputs for errors. - 7
- Next is a "single line comment." You'll learn moare about comments later, but they're a way to write non-code documentation about what's going on in the code.
- 8
- After the comment is another standard output, but this one has another new escape code
\t
which tells C++ to insert a TAB character at that point in the output. - 10
- This is the same as your
ex02.cpp
code that returns a 0 to the operating system, which means "no errors." - 11
- This
}
closes the block of code that was started by the{
on line 3. Make sure you know the names of these characters.
Break It
You should now try to break your code in as many ways as you can. Breaking your own code familiarize you with the kinds of errors you'll run into in the future. Some ways to break this code:
- Just delete a random character, then search online for the error.
- Remove the escape codes from the strings.
- Use incorrect escape codes.
- Have
return
at the end return something else. What happens if you return a string? - Delete the 1st line that includes
<iostream>
. - Include something random instead of
<iostream>
.
Further Study
As usual, here some extra challenges for you to attempt. Don't get too stressed if you can't solve them. Attempt them, then move on and possibly come back when you're stronger.
- Make sure you can name every character in this code and in
ex02.cpp
. If there's a character you can't name, try to remember it for next time. - Change your code to be like
ex02.cpp
using theuse namespace std;
line. Once you add this what do you have to change inex05.cpp
? - Which is better to use to print a newline? A
\n
escape code or theendl
fromex02.cpp
? Can you say why you like one or another? - Add some new things to say in this code and try some other escape codes.
Register for Learn C++ the Hard Way
Register to gain access to additional videos which demonstrate each exercise. Videos are priced to cover the cost of hosting.