How cout is written in the C++ program
For variables:
What is C++ cout?
- 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; }
Output:
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:
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:
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 to display the first and last names.
To make 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: