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++
#include <iostream>
using namespace std;
int main()
{
cout << "Welcome to GFG" ;
return 0;
}
|
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++
#include <iostream>
using namespace std;
int main()
{
string name = "Akshay" ;
int age = 18;
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++
#include <iostream>
using namespace std;
int main()
{
char gfg[] = "Welcome at GFG" ;
char ch = 'e' ;
cout.write(gfg, 6);
cout.put(ch);
return 0;
}
|
Program 4:
Below is the C++ program to illustrate the use of cout.precision():
C++
#include <iostream>
using namespace std;
int main()
{
double pi = 3.14159783;
cout.precision(5);
cout << pi << endl;
cout.precision(7);
cout << pi << endl;
return 0;
}
|