Printing with the Standard Library
The C++ Standard Library
The C++ Standard Library is a collection of containers, algorithms, and utilities that help make writing C++ easier. Instead of having to implement our own sorting algorithm, we can use the standard library’s std::sort
. Instead of implementing our own dynamically-sized array, we can use std::vector
.
The definitions for things in the standard library can be found in header files. Header files contain the interface definitions for the things we want to use. For example. if we want to use std::sort
, we need to include the algorithm
header. If we want to use std::vector
, we need to include the vector
header where the interface is defined.
We can include these headers with the #include
directive. The #include
directive tells our compiler driver to fetch the contents of the specified file, and paste it directly after the directive in our code (e.g., the content of the iostream
file when we write #include <iostream>
). These location of these headers is known to our compiler driver, so we don’t need to specify a full path to the files.
Relevant Links
Printing With The Standard Library
Printing gives us a way to surface the internal value of our program to the screen. Sometimes we print values to the screen because we want to debug a problem inside our program. Other times we want to print things to let the end-user know that the program is progressing normally.
There are a number of built in ways of printing values in C++. These include:
std::cout
std::print
printf
std::print
is still not currently supported by the majority of compiler vendors, and printf
is the method for printing that is more commonly used in C code, so we will only focus on std::cout
for now.
std::cout
is the character output stream object that has traditionally been used for printing. To use std::cout
we first must include the iostream
header (io
standing for input/output). To print using std::cout
, we use the <<
operator. Recall, operators have different meanings depending on the type we use them with.
We can chain together the <<
operator with different values we want to print. For example, we can print an integer, following by a string.
Printing works with both immediate values (like the string “Hello, world!\n”, or the integer 28) and values stored in variables. For example, we can create an integer variable called year
, set it to the value 2023
, and print it out.
Relevant Links
Why Do Things Start With std::
?
Avoiding naming conflicts can be difficult in large projects. One of the tools we have to avoid this in C++ is namespaces.
A namespace
is a scope that prevents the things inside from being mistaken for identically named things in other scopes. In the case of the Standard Library, everything is wrapped in the namespace std
.
To access things from a specific scope, we use ::
, the scope resolution operator. When we say std::cout
we’re saying we want to use cout
that lives in the scope std
.