Table of contents
1.
Introduction
2.
Streams in C++
3.
Standard output stream (cout)
4.
Standard input stream (cin)
5.
Un-buffered standard error stream (cerr)
6.
Buffered standard error stream (clog)
7.
Frequently Asked Questions
7.1.
What is the difference between cout and cerr?
7.2.
How do you read a full line of text using cin?
7.3.
When should you use clog instead of cerr?
8.
Conclusion
Last Updated: Nov 25, 2024
Easy

Cin and Cout in C++

Author Sinki Kumari
0 upvote
Career growth poll
Do you think IIT Guwahati certified course can help you in your career?

Introduction

If you are a programmer, you know very well that most of our programs completely depend on the user’s input, so we can say that communicating with users is a fundamental task. So, in order to solve this important aspect, C++ gives us the cin & cout streams, which provide a simple but powerful way to read input from users and display output on the screen. With the help of these streams, you can not only show your message but can take input from the user. These are essential tools for any C++ programmer to understand this. 

Cin and Cout in C++

In this article, we will discuss what cin and cout are, and how to use them in your C++ programs with the help of examples.

Streams in C++

In C++, input and output operations are performed using streams. A stream is a sequence of bytes that flow from a source to a destination. The source can be a keyboard, a file, or a network connection, while the destination can be the console, a file, or another program.

C++ provides several header files that define streams for different purposes:

<iostream>: This header file defines the standard input and output streams (cin, cout, cerr, clog) that are used to read from the keyboard and write to the console.
 

<iomanip>: This header file provides manipulators that can be used to format the output, such as setw, setprecision, and endl.
 

<fstream>: This header file defines file streams that can be used to read from and write to files.

These header files are essential for performing input/output operations in C++ programs.

Standard output stream (cout)

The standard output stream, represented by the cout object, is used to display output on the console. It is defined in the <iostream> header file and is part of the std namespace.

To use cout, you need to include the <iostream> header and use the insertion operator (<<) to send data to the console. 

For example: 

#include <iostream>
using namespace std;

int main() {
    string message = "Hello, World!";
    cout << message << endl;
    return 0;
}
You can also try this code with Online C++ Compiler
Run Code


In this code, we include the <iostream> header and use the using directive to bring the std namespace into scope. In the main function, we declare a string variable named message and assign it the value "Hello, World!". We then use cout with the insertion operator (<<) to display the message on the console, followed by endl, which inserts a newline character and flushes the stream.


When you run this program, it will output:

Hello, World!


You can use cout to display various types of data, such as integers, floating-point numbers, characters, and strings. You can also chain multiple insertion operations together:

cout << "The answer is " << 42 << endl;


This would output:

The answer is 42

Standard input stream (cin)

The standard input stream, represented by the cin object, is used to read input from the keyboard. Like cout, cin is defined in the <iostream> header file and belongs to the std namespace.

To read input using cin, you use the extraction operator (>>). For example:

#include <iostream>
using namespace std;

int main() {
    int age;
    cout << "Enter your age: ";
    cin >> age;
    cout << "You are " << age << " years old." << endl;
    return 0;
}
You can also try this code with Online C++ Compiler
Run Code


In this code, we declare an integer variable named age. We use cout to display a prompt message asking the user to enter their age. Then, we use cin with the extraction operator (>>) to read an integer value from the keyboard and store it in the age variable. Finally, we use cout to display a message that includes the user's age.

Output:

Enter your age:

 

After you enter a number and press Enter, it will output:

You are [age] years old.

 

You can read multiple values using cin by chaining extraction operations:

int num1, num2;
cin >> num1 >> num2;


This would read two integer values from the keyboard and store them in the variables num1 & num2.

When reading strings with cin, it's important to note that cin reads up to the first whitespace character (space, tab, or newline). To read a full line of text, you can use the getline function instead:

string fullName;
getline(cin, fullName);


This would read a full line of text from the keyboard & store it in the fullName variable.

Un-buffered standard error stream (cerr)

The un-buffered standard error stream, represented by the cerr object, is used to display error messages on the console. It is similar to cout but is specifically designed for error reporting.

The main difference between cout and cerr is that cerr is un-buffered, which means that the output is immediately sent to the console without any intermediate storage. This is useful for displaying error messages in real-time, especially when debugging programs.

Here's an example of using cerr:

#include <iostream>
using namespace std;

int main() {
    int num1 = 10, num2 = 0;
    if (num2 == 0) {
        cerr << "Error: Division by zero!" << endl;
        return 1;
    }
    int result = num1 / num2;
    cout << "Result: " << result << endl;
    return 0;
}
You can also try this code with Online C++ Compiler
Run Code


In this code, we check if num2 is zero before performing the division. If num2 is zero, we use cerr to display an error message indicating that division by zero is not allowed. We then return 1 to indicate that the program encountered an error and terminate the program.
 

If num2 is not zero, the division is performed, and the result is displayed using cout.
 

When you run this program with num2 set to zero, it will output:

Error: Division by zero!

 

The error message is immediately sent to the console through cerr, making it easier to identify and debug the issue.

Buffered standard error stream (clog)

The buffered standard error stream, represented by the clog object, is similar to cerr but with buffering enabled. Like cerr, clog is used to display error messages, but the output is stored in a buffer before being sent to the console.

The buffering behavior of clog is similar to that of cout. When you write to clog, the output is first stored in a buffer, and the buffer is flushed (i.e., the contents are sent to the console) when one of the following conditions is met:

1. The buffer becomes full.
 

2. A newline character (\n) is encountered.
 

3. The stream is explicitly flushed using the flush() function.


For example: 

#include <iostream>
using namespace std;


int main() {
    int num1 = 10, num2 = 0;
    if (num2 == 0) {
        clog << "Error: Division by zero!" << endl;
        return 1;
    }
    int result = num1 / num2;
    cout << "Result: " << result << endl;
    return 0;
}
You can also try this code with Online C++ Compiler
Run Code


This code is similar to the previous example using cerr, but we use clog instead to display the error message. The output will be the same as before:

Error: Division by zero!

 

However, because the clog is buffered, the error message may not appear immediately on the console. If there are other output operations before the error message, they may be displayed first, and the error message will be displayed when the buffer is flushed.

Note: In general, cerr is preferred for displaying error messages because it ensures immediate output, while clog can be used when buffering is desired for error messages.

Frequently Asked Questions

What is the difference between cout and cerr?

cout is buffered and used for normal output, while cerr is un-buffered and used for error messages.

How do you read a full line of text using cin?

To read a full line of text, use the getline function: getline(cin, stringVariable).

When should you use clog instead of cerr?

clog is used when buffering is desired for error messages, while cerr is preferred for immediate output.

Conclusion

In this article, we discussed the basics of input and output in C++ using cin and cout. We learned about the different stream objects (cout, cin, cerr, clog) and their purposes. We saw examples of how to read input from the user using cin and display output using cout. Finally, we discussed the differences between cerr and clog for error reporting. 

You can also check out our other blogs on Code360.

Live masterclass