cout declaration
extern ostream cout;
It is defined in <iostream> header file.
The cout object is ensured to be initialized during or before the first time an object of type ios_base::Init
is constructed. After the cout object is constructed, it is tied to cin
which means that any input operation on cin
executes cout.flush().
The "c" in cout
refers to "character" and 'out' means "output", hence cout
means "character output". The cout
object is used along with the insertion operator (<<) in order to display a stream of characters. The general syntax is:
cout << varName;
Or
cout << "Some String";
The extraction operator can be used more than once with a combination of variables, strings and manipulators (like endl):
cout << var1 << "Some String" << var2 << endl;
The cout object can also be used with other member functions such as put()
, write()
, etc. Some of the commonly used member functions are:
cout.put(char &ch):
Displays the character stored by ch.cout.write(char *str, int n):
Displays the first n character reading from str.cout.setf(option):
Sets a given option. Commonly used options are left, right, scientific, fixed, etc.cout.unsetf(option):
Unsets a given option.cout.precision(int n):
Sets the decimal precision to n while displaying floating-point values. Same as cout << setprecision(n).
Example 1: cout with insertion operator:
#include <iostream>
using namespace std;
int main()
{
int a,b;
char str[] = "Hello Programmers";
/* Single insertion operator */
cout << "Enter 2 numbers - ";
cin >> a >> b;
cout << str;
cout << endl;
/* Multiple insertion operator */
cout << "Value of a is " << a << endl << "Value of b is " << b;
return 0;
}
When you run the program, a possible output will be:
Enter 2 numbers - 6 17 Hello Programmers Value of a is 6 Value of b is 17
Example 2: cout with member function:
#include <iostream>
using namespace std;
int main()
{
char str[] = "Do not interrupt me";
char ch = 'm';
cout.write(str,6);
cout << endl;
cout.put(ch);
return 0;
}
When you run the program, a possible output will be:
Do not m