What is C++ cout and How to Use it?

How cout is written in the C++ program

cout << “text to display”;

cout << variable_name;

What is C++ cout?

The cout in C++:

  • The out in cout refers to output
  • cout is an object of the ostream class
  • The header file where this is defined is iostream
  • The ‘<<’ operator is used in conjunction with the cout object for displaying the output values or text i.e. cout <<
  • This operator ‘<<’ is called stream insertion
  • The standard output device is generally the monitor (a display screen) where cout object displays the output.
  • You may use as many cout objects as you want in the C++ programs.
  • It does not add a new line at the end of the output

Let us look at a few examples of using C++ cout object.

Display simple text using cout object

In this example, we simply display the text “Hello, C++ is awesome” by using cout object in conjunction with the ‘<<’ operator:

#include <iostream>

using namespace std;




int main() {

  cout << "Hello, C++ is awesome";

  return 0;

}

It output:

CPP-cout

The example of displaying text with a variable

This program displays the text and variable ‘name’ value. See the code below:

#include <iostream>

using namespace std;




int main() {

  string name = "Atiq";

  cout << "My Name is: " <<name;

  return 0;

}

Output:

CPP-cout-variable

Adding new line example using cout

We will display text, and variable value and add new lines at the end in the C++ program below:

#include <iostream>

using namespace std;




int main() {

  string favLang = "C++";

  cout << "My Favourite Programming Language is: " <<favLang <<"\n\n";

  return 0;

}

Output:

CPP-cout-newline

You can see, we used ‘\n’ twice in the above example and you may notice the difference in output.

Displaying two variable values using cout object example

Now we have fname (first name) and sname (surname) variables in this program. See how we combined the texts, variables, and new lines for displaying the first and last names clearly.

For making it more interesting, we will take the user entered first and last names by using the cin object:

#include <iostream>

using namespace std;




int main() {

  string fname, lname;

  //Display Message to Enter Name

  cout << "Please enter you first and last name? ";




  //Assign enter first and last name to string

  cin >> fname >> lname;




  //Displaying output

  cout << "First Name: " <<fname <<"\n" << "Last Name: " <<lname <<"\n";

  return 0;

}

Output:

CPP-cout-two-variables

 

Author - Atiq Zia

Atiq is the writer at jquery-az.com, an online tutorial website started in 2014. With a passion for coding and solutions, I navigate through various languages and frameworks. Follow along as we solve the mysteries of coding together!