Cout in C++



The predefined object cout is an instance of ostream class that displays the output to the user. The cout object is said to be attached to the standard output device, which usually is the screen. The cout object is used in conjunction with the stream insertion operator (<<) that inserts the data into the output stream and displays the data on the screen.

The syntax for using cout object with a single variable and multiple variables is given below −

// For single variable
cout << variable_name;

Or,

// For multiple variables
cout << variable1 << variable2 << ... << variableN;

where,

  • << is the insertion operator.
  • variable_name, variable1,..., variableN are the variable names whose values we want to display.

Read this chapter to get a good understanding of how cout works in C++.

Displaying Output with cout

The following example demonstrates how to display a single integer and multiple integers as output using cout to show the sum of the numbers −

#include <iostream>
using namespace std;
int main() {
    int num1 = 2;
    // Displaying single value
    cout << "Num1: " << num1 << endl;
     
    int num2 = 2, num3 = 5;
    // Displaying multiple values
    cout << "Num2: " << num2 << ", Num3: " << num3 << endl;
    cout << "Sum: " << num1 + num2 + num3 << endl;
    return 0;
}

The output of the above code is as follows −

Num1: 2
Num2: 2, Num3: 5
Sum: 9

Display Arrays with cout

This example demonstrated how to display an array as output using cout −

#include <iostream>
using namespace std;
int main() {

    int arr[5] = {1, 2, 3, 4, 5};
    int n = 5;
     
    cout << "Array elements: ";
    for (int i = 0; i < n; i++) {
	
        // Displaying array elements
        cout << arr[i] << " ";
    }
    cout << endl;
    return 0;
}

The output of the above code is as follows −

Array elements: 1 2 3 4 5 

C++ cout Object Functions

Below is a table of most commonly used functions of C++ cout object −

Functions Definition
cout.put() The cout.put() function writes a single character to the output stream.
cout.write() It writes a specified number of characters from a character array or string to the output stream.
cout.flush() The flush() function displays all pending output by forcing the output buffer to empty immediately.
cout.good() It checks the state of output stream and returns true if the output stream is in a good state with no errors.
cout.bad() It checks the state of output stream and returns true if an error occurs in the stream that can not be recovered.
cout.fail() It returns true for both recoverable and non-recoverable errors in the output stream.
cout.clear() It clears the error flags of the stream and reset it to good state. The clear() function is also used to set error states of output stream.
cout.width() The cout.width() function is used to set the minimum field width for the next output operation.
cout.precision() It sets the precision for floating-point numbers displayed in the output stream.
cout.fill() It sets the fill character that is used to pad output when the width is greater than the number of characters to be displayed.
cout.seekp() It is used to set the position of the put pointer in the output stream. It is generally used with file streams (ofstream).
cout.tellp() It returns the current position of the put pointer in the output stream. It is generally used with file streams (ofstream).
cout.eof() It returns true upon reaching end of file in the output stream.
cout.rdbuf() It returns the stream buffer object of cout that can be used to write to or redirect the output stream directly.

Here are the example codes of each member function listed above in the table −

In this example, we have used the cout.put() function to display "Hello C++", printing each character at a time in the output stream −

#include <iostream>
using namespace std;
int main() {

    cout << "Displaying characters: ";
    cout.put('H');
    cout.put('e');
    cout.put('l');
    cout.put('l');
    cout.put('o');
    cout.put(' ');
    cout.put('C');
    cout.put('+');
    cout.put('+');
    cout << endl;
    return 0;
}

The output of the above code is given below −

Displaying characters: Hello C++

Here is an example of cout.write() function to write 7 characters of the given text −

#include <iostream>
using namespace std;
int main(){

	char text[] = "Welcome to Tutorialspoint.";
	cout << "Full text: " << text << endl;
	cout << "First 7 characters: ";
	cout.write(text, 7);
	cout << endl;
	return 0;
}

The output of the above code is as follows −

Full text: Welcome to Tutorialspoint.
First 7 characters: Welcome

The following example demonstrates flushing the output buffer using cout.flush() function.

#include <iostream>
#include <chrono>
#include <thread>
using namespace std;
int main() {

	cout << "Processing";
	cout.flush(); // Ensures "Processing" is displayed immediately
	
	for(int i = 0; i < 5; i++) {
		this_thread::sleep_for(chrono::milliseconds(500));
		cout << ".";
		cout.flush(); // Ensures each dot appears immediately
	}
	cout << " Done!" << endl;
	return 0;
}

The output of the above code is as follows −

Processing..... Done!

Here is an example of width() function that sets the minimum field width for the next output operation −

#include <iostream>
using namespace std;
int main() {
    cout << "Without width:" << endl;
    cout << "123" << endl;
    cout << "45" << endl;
    
    cout << "With width(5):" << endl;
    cout.width(5);
    cout << "123" << endl;
    cout << "With width(10):" << endl;
    cout.width(10);
    cout << "45" << endl;
    return 0;
}

The output of the above code is as follows −

Without width:
123
45
With width(5):
123
With width(10):
45

In this example, the precision() function sets the number of digits to display for floating-point numbers.

#include <iostream>
using namespace std;
int main() {
    double pi = 3.14159265359;
    cout << "Default precision: " << pi << endl;
    cout.precision(3);
    cout << "Precision 3: " << pi << endl;
    return 0;
}

The output of the above code is as follows −

Default precision: 3.14159
Precision 3: 3.14

In this example, we are checking the state of the output stream. For successful operations, it prints success message and for failed operations, it prints a message of output stream error.

#include <iostream>
using namespace std;
int main() {
	int num = 345;
	cout << "Displaying number: " << num << endl;
	if (cout.good()) {
		cout << "Output stream is in good state" << endl;
	} else {
		cout << "Output stream has errors" << endl;
	}
	return 0;
}

The output of the above code is as follows −

Displaying number: 345
Output stream is in good state

The following example demonstrates the use of cout.bad(). It returns true only for non-recoverable errors.

#include <iostream>
using namespace std;
int main() {
    cout << "Hello World!" << endl;
    if (cout.bad()) {
        cout << "Bad error occurred!" << endl;
    } else {
        cout << "No bad error in output stream" << endl;
    }
    return 0;
}

The output of the above code is as follows −

Hello World!
No bad error in output stream

In this example, the cout.fail() checks if any output operation has failed −

#include <iostream>
using namespace std;

int main() {
    cout << "Hello World" << endl;

    // Check if the previous output failed
    if (cout.fail()) {
        cout << "Something went wrong while writing to output!" << endl;
    } else {
        cout << "Output was successful." << endl;
    }

    return 0;
}

The output of the above code is as follows −

Hello World
Output was successful.

The following example clears the error flags when an error occurs in the output stream −

#include <iostream>
using namespace std;
int main() {

     cout << "Normal output operation" << endl;
     if (cout.fail()){
          cout << "Output error detected. Clearing error..." << endl;
          cout.clear();
          cout << "Error flags cleared!" << endl;
     } else {
          cout << "Output stream is working properly" << endl;
     }
     return 0;
}

The output of the above code is as follows −

Normal output operation
Output stream is working properly

In this example, we are using "*" and "0" as a fill character for padding the output when using cout.width() function −

#include <iostream>
using namespace std;
int main() {

     cout << "Default fill character:" << endl;
     cout.width(10);
     cout << "123" << endl;
     
     cout << "Using '*' as fill character:" << endl;
     cout.fill('*');
     cout.width(10);
     cout << "123" << endl;
     
     cout << "Using '0' as fill character:" << endl;
     cout.fill('0');
     cout.width(10);
     cout << "456" << endl;
     return 0;
}

The output of the above code is as follows −

Default fill character:
123
Using '*' as fill character:
*******123
Using '0' as fill character:
0000000456

Conclusion

In this chapter, we understood the cout object and its usage along with its member functions and their respective example codes.

Advertisements