---
description: What are Streams in C++? C++ provides users with a number of libraries that they can use to perform input/output tasks. These tasks are done in the form of byte sequences, popularly called streams. Th
title: C++ Basic Input/Output: Cout, Cin, Cerr Example
image: https://www.guru99.com/images/cpp-basic-input-output.png
---

 

[Skip to content](#main) 

**⚡ Smart Summary**

C++ input and output operations rely on stream objects that move data as byte sequences between programs and devices, with cin reading keyboard input and cout, cerr, and clog writing output to the screen.

* 🔘 **Streams:** Input and output tasks travel as byte sequences called streams, moving data between main memory and devices.
* 📥 **Header files:** The iostream, iomanip, and fstream libraries define the objects and manipulators used for basic input and output.
* 🖨️ **cout and cin:** The cout object prints with the insertion operator, while cin reads values with the extraction operator.
* ⚠️ **cerr and clog:** Both report errors, yet cerr stays unbuffered for immediate display while clog buffers messages first.
* 🛠️ **Error handling:** The good, bad, fail, and eof checks read stream state, so failed operations are caught safely.
* 🤖 **AI assistance:** AI coding assistants such as GitHub Copilot generate cin and cout boilerplate from a short comment or function name.

[ Read More ](javascript:void%280%29;) 

![C++ Basic Input Output](https://www.guru99.com/images/cpp-basic-input-output.png)

## What are Streams in C++?

C++ provides users with a number of libraries that they can use to perform input/output tasks. These tasks are done in the form of byte sequences, popularly called streams.

The streams are divided into two:

### Types of streams

* **Input Stream:** This is a type of stream where the bytes flow from a device such as a keyboard to the main memory.
* **Output Stream:** This is a type of stream where the bytes flow in the opposite direction, that is, from main memory then to the device such as display screen.

## How do streams work?

C++ streams work as follows:

1. First, a stream is initialized with the right type.
2. Next, you should state where the I/O will occur using get/put pointers.
3. After getting to the right location in a stream, you can perform input and output tasks using >> and << operators, respectively.

## Function Table

The following are the functions provided in the stream.h header file:

| Class       | Functions                                                                                                           |
| ----------- | ------------------------------------------------------------------------------------------------------------------- |
| Filebuf     | It sets file buffers to read/write. It has close() and open() functions in it                                       |
| fstreambase | It’s the base class for the classes ifstream, fstream, and ofstream. Its operations are common to the file streams. |
| ifstream    | It’s an input file stream class for providing input operations.                                                     |
| ofstream    | It’s an output file stream class for providing output operations.                                                   |
| fstream     | It’s an input/output stream class. It supports simultaneous input/output operations.                                |

## C++ Header files for Input/ Output

C++ provides three libraries that come with functions for performing basic input/out tasks. They include:

* **Iostream:** It’s an acronym for standard input/output stream. This header file comes with definitions for objects like cin/ cout/cerr.
* **Iomanip:** It’s an acronym for input/output manipulators. The library comes with functions that can be used for the manipulation of streams. It contains definitions for objects like setw, setprecision, and others.
* **Fstream:** This is a header file for describing the file stream. It handles data that is read from file as input or that is written to a file, the output.

The cin and cout keywords are very popular in C++. They are used for taking inputs and printing outputs, respectively. To use them, you must include iostream header file in your program. The reason is that they are defined in that header file. Failure to include the iostream header file will generate an error. This results from a failure by the C++ compiler to understand the meaning of the keywords.

The major objects defined in the iostream header file are cin, cout, cerr, and clog. Let’s discuss them.

## std::cout

The cout object is an instance of the iostream class. It is used for producing output on a standard output device, which is normally the screen. It’s used together with the stream insertion operator (<<).

### Example

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

	char welcome[] = "Welcome to Guru99";

	cout << welcome << endl;

	return 0;
}

**Output:**

[](https://www.guru99.com/images/2/062520%5F0610%5FCBasicInput1.png)

Here is a screenshot of the code:

[](https://www.guru99.com/images/2/062520%5F0610%5FCBasicInput2.png)

**Code Explanation:**

1. Include the iostream header file where the cout object is defined.
2. Include the std namespace so that we don’t have to call it when using its classes.
3. Call the main() function. The program code should be added within its body. The opening curly brace { marks the beginning of its body.
4. Create a character variable named welcome to hold the string Welcome to Guru99.
5. Print the value of the string welcome on the console. The endl is a C++ keyword meaning end line. It moves the cursor to begin printing text on the next line.
6. The program must return value upon successful execution.
7. End of the body of function main().

### RELATED ARTICLES

* [For Loop in C++ with Syntax & Program EXAMPLES ](https://www.guru99.com/cpp-for-loop.html "For Loop in C++ with Syntax & Program EXAMPLES")
* [C++ do…while loop with Examples ](https://www.guru99.com/cpp-do-while-loop.html "C++ do…while loop with Examples")
* [Top 24 C++ Interview Questions and Answers (PDF) ](https://www.guru99.com/cpp-interview-questions.html "Top 24 C++ Interview Questions and Answers (PDF)")
* [Hello World Program in C++ with Code Explanation ](https://www.guru99.com/cpp-hello-world-program.html "Hello World Program in C++ with Code Explanation")

## std::cin

The cin object is an instance of the istream class. It reads input from the input device, the keyboard. It is normally used together with the extraction operator (>>). The extraction object is responsible for extracting data entered through the keyboard from the cin object.

### Example

The following example demonstrates how to use the cin keyword in [C++](https://www.guru99.com/cpp-tutorial.html):

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

	cout << "Enter a number:";
	cin >> number;
	cout << "\nYou entered: " << number;

	return 0;
}

**Output:**

[](https://www.guru99.com/images/2/062520%5F0610%5FCBasicInput3.png)

Here is a screenshot of the code:

[](https://www.guru99.com/images/2/062520%5F0610%5FCBasicInput4.png)

**Code Explanation:**

1. Include the iostream header file into our program. The cin object is defined in this header file.
2. Include the std namespace to use its classes. You will not have to call std when using its classes.
3. Call the main() function. The program code should be added within its body.
4. The start of the body of the program.
5. Declare an [integer variable](https://www.guru99.com/cpp-variables-types.html) named number.
6. Print a message on the screen prompting the user to enter a number.
7. Read the value entered by the user on the console from the keyboard.
8. Print the value read above on the console alongside other text.
9. The program should return a value if it executes successfully.
10. End of the body of the main function.

## std::cerr

The cerr object forms the standard error stream for outputting errors in C++. Cerr is an instance of the ostream class. The cerr object is unbuffered. This means it’s used when an error message is to be displayed immediately.

Since it’s unbuffered, it doesn’t store error message for a later display. It’s used together with the stream insertion operator (<<).

### Example

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

	cerr << "An Error occurred!";

	return 0;
}

**Output:**

[](https://www.guru99.com/images/2/062520%5F0610%5FCBasicInput5.png)

Here is a screenshot of the code:

[](https://www.guru99.com/images/2/062520%5F0610%5FCBasicInput6.png)

**Code Explanation:**

1. Include iostream header file where the cerr object has been defined.
2. Include the std namespace so that we don’t have to call it when using its classes.
3. Call the main() function. The program logic should be added within its body. The opening curly brace marks the beginning of the function’s body.
4. Use the cerr object to print an error on the console.
5. The program must return a value upon successful execution.
6. End of the body of the main function.

## std::clog

The clog object is an instance of the ostream class. It’s used to show errors on the standard display, the monitor. It’s similar to the cerr object, but it’s buffered. Since it’s buffered, it stores the error message in buffer till the buffer is filled/flushed. It’s used together with the stream insertion operator (<<).

### Example

#include <iostream>
using namespace std;
int main() {
	clog << "An Error occurred!";
	return 0;
}

**Output:**

[](https://www.guru99.com/images/2/062520%5F0610%5FCBasicInput7.png)

Here is a screenshot of the code:

[](https://www.guru99.com/images/2/062520%5F0610%5FCBasicInput8.png)

**Code Explanation:**

1. Including the iostream header file in which the clog object is defined.
2. Including the std namespace so that we can use its classes without calling it.
3. Calling the main() function. The program logic should be added within its body. The { marks the beginning of the function’s body.
4. Use the clog object to print an error on the standard output, the monitor.
5. The program must return a value upon successful completion.
6. The end of the body of function main().

## Error handling with IO streams

The same stream objects also report whether an operation succeeded, which stream state checks reveal.

To check whether a stream is valid or not, you can use it as a Boolean.

Here is an example:

ifstream file( "myfile.txt" );
if ( ! file )
{
        cout << "File NOT opened!" << endl;
}

To get more details for the stream status, you can use these functions:

* good()- will return true if all is okay.
* bad()- will return true if a fatal error occurs.
* fail()- will return true after unsuccessful stream operation.
* eof()- will return true if it reaches end of a file.

To know whether a particular read/write operation failed, test the read result.

For example, to check whether user entered a valid integer, do this:

int p;
if ( cin >> p ) 
{
        cout << "Enter valid number" << endl;
}

## FAQs

🔀 What is the difference between cout and printf in C++?

The cout object is type-safe and uses the insertion operator, so it detects each value’s type automatically. C’s printf relies on format specifiers such as %d that must match the arguments manually.

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

The extraction operator stops at the first space, so cin reads only one word. To capture a whole line with spaces, call getline(cin, variable), which reads up to the newline character.

⏱️ Should you end output with endl or a newline character in C++?

Both start a new line, but endl also flushes the output buffer each time, which can slow busy loops. Prefer a plain newline and reserve endl for when the buffer must flush immediately.

🧩 What does using namespace std do for cin and cout?

The cin, cout, cerr, and clog objects live in the std namespace. Writing using namespace std lets you type cout rather than std::cout. Large projects often keep the explicit std prefix to avoid clashes.

🎚️ How do you set output width and decimal precision in C++?

Include the iomanip header and use manipulators with cout. The setw manipulator reserves a field width, and setprecision sets how many digits appear, formatting numbers and columns without changing the stored values.

🔁 Can you send cout and cerr to different destinations?

Yes. Because cout and cerr are separate streams, a shell can redirect normal output to a file while errors still reach the screen. In code, rdbuf can point a stream at another buffer.

🤖 Can AI tools generate C++ input and output code automatically?

Yes. AI coding assistants read a comment or function name and produce cin and cout statements, plus the iostream include and a formatted prompt. Reviewing the generated stream logic for edge cases stays wise.

🐙 Does GitHub Copilot help write C++ cin and cout code?

Yes. [GitHub Copilot](https://github.com/features/copilot) completes cout formatting, cin validation loops, and cerr error checks as you type. Its 2026 C++ code intelligence adds semantic symbol awareness, so multi-file suggestions stay consistent.

#### Summarize this post with:

ChatGPT Perplexity Grok Google AI 

**Stay Updated on AI** **Get Weekly AI Skills, Trends, Actionable Advice.** 

##### Sign up for the newsletter

Subscribe for Free 

You have successfully subscribed.  
Please check your inbox. 

![AI-Newsletter]() Chosen by over **350,000+** professionals 

[Scroll to top ](#wrapper)Scroll to top 

× 

Toggle Menu Close 

Search for: 

Search

```json
{"@context":"https://schema.org","@graph":[{"@type":"Organization","@id":"https://www.guru99.com/#organization","name":"Guru99","sameAs":["https://www.facebook.com/Guru99Official","https://twitter.com/guru99com"],"logo":{"@type":"ImageObject","@id":"https://www.guru99.com/#logo","url":"https://www.guru99.com/images/guru99-logo-v1-150x59.png","contentUrl":"https://www.guru99.com/images/guru99-logo-v1-150x59.png","caption":"Guru99","inLanguage":"en-US"}},{"@type":"WebSite","@id":"https://www.guru99.com/#website","url":"https://www.guru99.com","name":"Guru99","publisher":{"@id":"https://www.guru99.com/#organization"},"inLanguage":"en-US"},{"@type":"ImageObject","@id":"https://www.guru99.com/images/cpp-basic-input-output.png","url":"https://www.guru99.com/images/cpp-basic-input-output.png","width":"700","height":"250","caption":"C++ Basic Input/Output","inLanguage":"en-US"},{"@type":"BreadcrumbList","@id":"https://www.guru99.com/input-output-cplusplus.html#breadcrumb","itemListElement":[{"@type":"ListItem","position":"1","item":{"@id":"https://www.guru99.com","name":"Home"}},{"@type":"ListItem","position":"2","item":{"@id":"https://www.guru99.com/cpp","name":"CPP"}},{"@type":"ListItem","position":"3","item":{"@id":"https://www.guru99.com/input-output-cplusplus.html","name":"C++ Basic Input/Output: Cout, Cin, Cerr Example"}}]},{"@type":"WebPage","@id":"https://www.guru99.com/input-output-cplusplus.html#webpage","url":"https://www.guru99.com/input-output-cplusplus.html","name":"C++ Basic Input/Output: Cout, Cin, Cerr Example","dateModified":"2026-07-13T13:21:53+05:30","isPartOf":{"@id":"https://www.guru99.com/#website"},"primaryImageOfPage":{"@id":"https://www.guru99.com/images/cpp-basic-input-output.png"},"inLanguage":"en-US","breadcrumb":{"@id":"https://www.guru99.com/input-output-cplusplus.html#breadcrumb"}},{"@type":"Person","@id":"https://www.guru99.com/author/benjamin","name":"Benjamin Walker","description":"I'm Benjamin Walker, an expert in C, C++, and C# programming, providing resources to enhance your coding proficiency and project outcomes.","url":"https://www.guru99.com/author/benjamin","image":{"@type":"ImageObject","@id":"https://www.guru99.com/images/benjamin-walker-author.png","url":"https://www.guru99.com/images/benjamin-walker-author.png","caption":"Benjamin Walker","inLanguage":"en-US"},"worksFor":{"@id":"https://www.guru99.com/#organization"}},{"articleSection":"CPP","headline":"C++ Basic Input/Output: Cout, Cin, Cerr Example","description":"What are Streams in C++? C++ provides users with a number of libraries that they can use to perform input/output tasks. These tasks are done in the form of byte sequences, popularly called streams. Th","keywords":"bigdata, programming, database, server","speakable":{"@type":"SpeakableSpecification","cssSelector":[".entry-title",".summary"]},"@type":"Article","author":{"@id":"https://www.guru99.com/author/benjamin","name":"Benjamin Walker"},"dateModified":"2026-07-13T13:21:53+05:30","image":{"@id":"https://www.guru99.com/images/cpp-basic-input-output.png"},"copyrightYear":"2026","name":"C++ Basic Input/Output: Cout, Cin, Cerr Example","subjectOf":[{"@type":"FAQPage","mainEntity":[{"@type":"Question","name":"What is the difference between cout and printf in C++?","acceptedAnswer":{"@type":"Answer","text":"The cout object is type-safe and uses the insertion operator, so it detects each value\u2019s type automatically. C\u2019s printf relies on format specifiers such as %d that must match the arguments manually."}},{"@type":"Question","name":"How do you read a full line of text with spaces using cin?","acceptedAnswer":{"@type":"Answer","text":"The extraction operator stops at the first space, so cin reads only one word. To capture a whole line with spaces, call getline(cin, variable), which reads up to the newline character."}},{"@type":"Question","name":"Should you end output with endl or a newline character in C++?","acceptedAnswer":{"@type":"Answer","text":"Both start a new line, but endl also flushes the output buffer each time, which can slow busy loops. Prefer a plain newline and reserve endl for when the buffer must flush immediately."}},{"@type":"Question","name":"What does using namespace std do for cin and cout?","acceptedAnswer":{"@type":"Answer","text":"The cin, cout, cerr, and clog objects live in the std namespace. Writing using namespace std lets you type cout rather than std::cout. Large projects often keep the explicit std prefix to avoid clashes."}},{"@type":"Question","name":"How do you set output width and decimal precision in C++?","acceptedAnswer":{"@type":"Answer","text":"Include the iomanip header and use manipulators with cout. The setw manipulator reserves a field width, and setprecision sets how many digits appear, formatting numbers and columns without changing the stored values."}},{"@type":"Question","name":"Can you send cout and cerr to different destinations?","acceptedAnswer":{"@type":"Answer","text":"Yes. Because cout and cerr are separate streams, a shell can redirect normal output to a file while errors still reach the screen. In code, rdbuf can point a stream at another buffer."}},{"@type":"Question","name":"Can AI tools generate C++ input and output code automatically?","acceptedAnswer":{"@type":"Answer","text":"Yes. AI coding assistants read a comment or function name and produce cin and cout statements, plus the iostream include and a formatted prompt. Reviewing the generated stream logic for edge cases stays wise."}},{"@type":"Question","name":"Does GitHub Copilot help write C++ cin and cout code?","acceptedAnswer":{"@type":"Answer","text":"Yes. GitHub Copilot completes cout formatting, cin validation loops, and cerr error checks as you type. Its 2026 C++ code intelligence adds semantic symbol awareness, so multi-file suggestions stay consistent."}}]}],"@id":"https://www.guru99.com/input-output-cplusplus.html#schema-1142952","isPartOf":{"@id":"https://www.guru99.com/input-output-cplusplus.html#webpage"},"publisher":{"@id":"https://www.guru99.com/#organization"},"inLanguage":"en-US","mainEntityOfPage":{"@id":"https://www.guru99.com/input-output-cplusplus.html#webpage"}}]}
```
