C++ - C++ Output - Programming Languages

How To Print in C++

Most coding revolves around inputting data into something like an integrated development environment (IDE) to create a program that accomplishes a task. However, you’ll likely need that program to output data at some point. In this guide, we’ll look at how to print text in C++, covering ways to print a string and best format them.

What Is a String?

A C++ string is a variable that stores a sequence of characters, usually representing a word or phrase. We can call upon this variable later for use in our program by using the string command. If we’re looking to output a string, we can type the string we want to print directly into our program without first storing it as a variable. Here is an example:

std::cout << "No need to store this string"; 

Types of Output: Ways To Print a String

C++ itself provides one way to print a string, but C++ can also use code from C to reach the same result. Here are the top ways that C++ developers print strings in the language.

The std::cout Object

Std::cout is the preferred way to print a string in C++. To better understand this object, let’s take a closer look at its components.

When C++ first came to be, all objects like cout were part of a global namespace. However, this led to conflicts with user-created objects bearing the same name. Programs wouldn’t know which object to use and would not compile.

To rectify this problem, the standard namespace (abbreviated: std) was created to store objects like cout to be used for their desired purpose. As a result, developers can now use an object like cout to print a string but must point to it in the standard namespace.

The scope resolution operator (::) is used to identify the namespace that our object belongs to. The object goes on the right and its corresponding namespace goes on the left. When we type std::cout, we’re telling the program that we need to use the cout that exists in the std namespace.

Finally, the cout object is the bit of code we need to print text in C++. This object is what tells the program to output the string that follows.

#include <iostream>

int main()
{
  std::cout << "Thanks for viewing my code!";
  return 0;
}

In this simple program, we’re reaching into the std namespace to use the cout object to print some text. Here’s what we would see on the screen:

Thanks for viewing my code!

Cout can do more than just print text; we can also use it to print variables:

#include <iostream>
using namespace std;
int main()
{
  int x = 10;
  cout << "x is equal to " << x; 
  return 0;
}

Here, cout outputs the string and also the value of the variable:

x is equal to 10

The Using Directive

It’s possible to make a declaration at the beginning of our code with a using directive. This tells the program to use a particular namespace when resolving identifiers below its location in the code. Any identifier without a prefix will be assumed to be in the std namespace.

#include <iostream>
using namespace std;
int main()
{
  cout << "Thanks for reading my code!";
  return 0;
}

Since cout in this example has no prefix, the compiler searches the std namespace and uses the cout from there. We end up with the same output as in our first program above:

Thanks for viewing my code!

Just be careful not to declare a cout of your own, or the program will not know which one to use while compiling. 

In the following example, we’ll declare our own cout function and leave the program guessing which one we’re referring to.

#include <iostream>

using namespace std;
int cout()
{
  return 5;
}  int main()
{
    cout << "This code doesn't work!";
    return 0;
}

Since we told the program to look in the std namespace any time it sees an identifier without a prefix, it finds both the cout in the std namespace and the cout we declared, and does not know which one we want to use.

If you ever find yourself in this situation, it’s best to omit the using directive and instead declare the namespace directly with the identifier.

The Function printf

printf is a C function that you may use in C++ to print from a program. Printf uses a somewhat similar structure to cout, but since it comes from C, the notable difference is that it requires a format specifier.

This format specifier is used to identify the output type of the variable. The format looks like this:

printf("string and format specifier", variable_name);

Here are a few of the most common format specifiers that printf uses:

Format SpecifierDefinition
%dsigned decimal integer
%iunsigned decimal integer
%ccharacter
%sstring of characters

Here’s an example of printf in action:

#include <stdio.h>
main(){
  char ch = 'N';
  printf("We've chosen the character %c\n", ch);
  int x = 20;
  printf("x is equal to %d\n", x);
}

When this program compiles, it generates the following output:

We've chosen the character N
x is equal to 20

The system Function

The system function is located in the standard library of C++. It passes commands to the command processor for execution and returns the command upon completion of execution. Here’s an example:

#include <stdlib.h>
int main(int argc, char** argv)
{
  system("echo Thanks for reading my code!\n");
} 

The system creates a subprocess that starts the default shell. It then runs a command in that shell. 

This returns the following output:

Thanks for viewing my code!

Which C++ Print Method Should You Use?

Each method described above can be used to print output in C++. However, printf and the system function have their origins in the C programming language. The cout object is the only print method specifically created for C++.

cout is an object of the ofstream type. C++ was designed around object-oriented programming and has completely different syntax compared to the functions deriving from C. Accordingly, cout is considered the standard way of printing strings in C++. 

Printf also requires a format specifier. Cout removes that need as it makes that determination for you. Cout is thus easier to use and understand.

Output Formatting

If you do not want your output to be left-justified or on a single line, we’ll give you a few alternatives for formatting your output.

The Endl Manipulator

Endl is effectively a carriage return in C++. Putting endl at the end of a cout statement will place the following line of text on a new line:

#include <iostream>

using namespace std;

int main()
{
  cout << "This is a" << endl;
  cout << "weird place for a new line";
  return 0;
}

Compiling this code gives us the following output:

This is a
weird place for a new line

Removing the endl manipulator would keep the print output on the same line, even though we’ve used two cout statements.

The setw Manipulator

The setw manipulator shifts the field width of only the text that follows it by a set number of spaces:

#include <iostream>
#include <iomanip>

using namespace std;

int main()
{
  cout << "No " << "change " << "here" << endl;
  cout << "Shift some text " << setw(25) << "to the right" << endl;
  cout << setw(50) << "Or shift it all" << endl;
  return 0;
}

Running this code shows how we’re able to position a string as we see fit:

No change here
Shift some text              to the right
                                 Or shift it all

An Unusual Way To Print a String

Who said printing a simple string in C++ has to be easy? There are, in theory, innumerable ways to do so. To be frank, some of them are just a lot of extra work for little gain. Take this example:

#include<stdio.h>
#include<stdlib.h>
int main(int argc,char**argv)
{
union a{
int b;
char c[4];
};
union a*d[(argc>>=31)+3];
while(argc++<4) d[argc-2]=(union a*)malloc(sizeof(union a));
d[0]->b=1819043144;
d[1]->b=1870078063;
d[2]->b=560229490;
printf("%s%s%s\n",d[0]->c,d[1]->c,d[2]->c);return 0;} 

This chunk of code uses a union function and ASCII to generate the characters needed for the string. The union serves as both an int and a char array to tie it all together. The complex printf function finally gives us our output:

Hello world!

Thankfully, as we saw earlier, C++ makes it much easier to say “hello.”

Taking Your C++ Skills to the Next Level

As this guide has made clear, printing output is an essential part of C++ programming.

Ready to level up your C++ game? We offer an expert-taught online program that will take you through five real-world projects, culminating with you coding your very own C++ application.

Enroll in Udacity’s C++ Nanodegree program today!

Start Learning