C++ provides the 'cout' object, which is an instance of the 'iostream' class and is commonly used to display output on the screen. For formatted output, 'cout' is used with the insertion operator '<<'.
Example:
#include <iostream>
using namespace std;
int main(){
cout << "GeeksforGeeks!";
return 0;
}
Output
GeeksforGeeks!
Explanation:
- #include <iostream> includes the input-output stream library.
- using namespace std; allows using cout without the std:: prefix.
- cout << "GeeksforGeeks!"; prints the text inside double quotes exactly as it appears.
- The return 0; statement indicates successful program execution.
C++ Program Using cout Manipulator
Below is the C++ program to demonstrate a manipulator that can be used with the cout object:
#include <iostream>
using namespace std;
int main()
{
char str[] = "Geeksforgeeks";
cout << " A computer science portal for geeks - " << str;
return 0;
}
Output
A computer science portal for geeks - Geeksforgeeks
Explanation:
- The text written inside the double quotes in the cout statement is printed exactly as it appears, while the value stored in the variable str is fetched at runtime and displayed after it.
C++ Program to Take Input and Display Output
In this example, the program reads a city name entered by the user and stores it in the name variable. After taking the input, the program displays the entered city name on the screen.
#include <iostream>
using namespace std;
int main(){
char name[30];
cin >> name;
cout << name;
return 0;
}
Input:
Mumbai
Output:
Mumbai
Explanation:
- char name[30]: Creates a character array (string) of capacity 30.
- cin >> name: Takes user input into the 'name' variable.