cout in C++
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++
// 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; } |
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++
// 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; } |
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++
// 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; } |
Welcome
Program 4:
Below is the C++ program to illustrate the use of cout.precision():
- C++
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; } |
3.1416 3.141598
Summer-time is here and so is the time to skill-up! More than 5,000 learners have now completed their journey from basics of DSA to advanced level development programs such as Full-Stack, Backend Development, Data Science.
And why go anywhere else when our DSA to Development: Coding Guide will help you master all this in a few months! Apply now to our DSA to Development Program and our counsellors will connect with you for further guidance & support.