Open In App

cout in C++

Improve
Improve
Improve
Like Article
Like
Save Article
Save
Share
Report issue
Report

The cout object in C++ is an object of class iostream. It is defined in iostream header file. It is used to display the output to the standard output device i.e. monitor. It is associated with the standard C output stream stdout. The data needed to be displayed on the screen is inserted in the standard output stream (cout) using the insertion operator(<<).

Program 1:

Below is the C++ program to implement cout object:

C++




// C++ program to illustrate the use
// of cout object
#include <iostream>
using namespace std;
 
// Driver Code
int main()
{
    // Print standard output
    // on the screen
    cout << "Welcome to GFG";
 
    return 0;
}


Output: 

Welcome to GFG

 

Note: More than one variable can be printed using the insertion operator(<<) with cout.

Program 2:

Below is the C++ program to implement the above approach:

C++




// C++ program to illustrate printing
// of more than one statement in a
// single cout statement
#include <iostream>
using namespace std;
 
// Driver Code
int main()
{
    string name = "Akshay";
    int age = 18;
 
    // Print multiple variable on
    // screen using cout
    cout << "Name : " << name << endl
         << "Age : " << age << endl;
 
    return 0;
}


Output: 

Name : Akshay
Age : 18

 

The cout statement can also be used with some member functions:

  • cout.write(char *str, int n): Print the first N character reading from str.
  • cout.put(char &ch): Print the character stored in character ch.
  • cout.precision(int n): Sets the decimal precision to N, when using float values.

Program 3:

Below is the implementation of the member functions of the cout.write() and cout.put():

C++




// C++ program to illustrate the use
// of cout.write() and cout.put()
#include <iostream>
using namespace std;
 
// Driver Code
int main()
{
    char gfg[] = "Welcome at GFG";
    char ch = 'e';
 
    // Print first 6 characters
    cout.write(gfg, 6);
 
    // Print the character ch
    cout.put(ch);
    return 0;
}


Output: 

Welcome

 

Program 4:

Below is the C++ program to illustrate the use of cout.precision():

C++




// C++ program toillustrate the use
// of cout.precision()
#include <iostream>
using namespace std;
 
// Driver Code
int main()
{
    double pi = 3.14159783;
 
    // Set precision to 5
    cout.precision(5);
 
    // Print pi
    cout << pi << endl;
 
    // Set precision to 7
    cout.precision(7);
 
    // Print pi
    cout << pi << endl;
 
    return 0;
}


Output: 

3.1416
3.141598

 



Last Updated : 08 Nov, 2022
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads