Cpp Basic Input Output
## Introduction to C++ Input/Output
The C++ standard library provides a rich set of Input/Output (I/O) capabilities. In C++, I/O operations occur in **streams**, which are sequences of bytes.
* **Input Operation:** If the stream of bytes flows from a device (such as a keyboard, disk drive, or network connection) into main memory, it is called an input operation.
* **Output Operation:** If the stream of bytes flows from main memory to a device (such as a display screen, printer, disk drive, or network connection), it is called an output operation.
---
## I/O Library Header Files
To perform I/O operations in C++, you must include specific header files. The most commonly used headers are:
| Header File | Description |
| :--- | :--- |
| `` | Defines the standard stream objects: `cin` (standard input), `cout` (standard output), `cerr` (unbuffered standard error), and `clog` (buffered standard error). |
| `` | Declares services used to perform formatted I/O with parameterized stream manipulators, such as `setw` and `setprecision`. |
| `` | Declares services for user-controlled file processing. |
---
## Standard Output Stream (`cout`)
The predefined object `cout` is an instance of the `ostream` class. The `cout` object is "connected" to the standard output device, which is typically the display screen.
To send data to the output stream, `cout` is used in conjunction with the **stream insertion operator** (`<<`).
### Example
```cpp
#include
using namespace std;
int main()
{
char str[] = "Hello C++";
// Outputting a string literal and a variable to the console
cout << "Value of str is : " << str << endl;
return 0;
}
```
### Output
```text
Value of str is : Hello C++
```
### Key Considerations
* **Type Safety:** The C++ compiler automatically detects the data type of the variable to be outputted and selects the appropriate overloaded `<<` operator to display the value.
* **Chaining:** The stream insertion operator `<<` can be chained multiple times in a single statement, as shown in the example above.
* **`endl` Manipulator:** The `endl` manipulator is used to insert a newline character (`\n`) into the output stream and flush the stream buffer.
---
## Standard Input Stream (`cin`)
The predefined object `cin` is an instance of the `istream` class. The `cin` object is attached to the standard input device, which is usually the keyboard.
To read data from the input stream, `cin` is used in conjunction with the **stream extraction operator** (`>>`).
### Example
```cpp
#include
using namespace std;
int main()
{
char name;
cout << "Please enter your name: ";
// Reading user input into the 'name' variable
cin >> name;
cout << "Your name is: " << name << endl;
return 0;
}
```
### Output
```text
Please enter your name: cplusplus
Your name is: cplusplus
```
### Key Considerations
* **Type Matching:** The compiler matches the extracted data with the variable's data type. If the input does not match the expected type, the stream enters a fail state.
* **Whitespace Delimiter:** By default, the `>>` operator treats whitespace (spaces, tabs, and newlines) as delimiters. If you input a full name like "John Doe", `cin >> name` will only read "John". To read an entire line containing spaces, use `cin.getline()` or `getline(cin, string_variable)`.
* **Chaining Inputs:** You can chain multiple extraction operators to read multiple values in a single statement:
```cpp
cin >> name >> age;
```
This is equivalent to:
```cpp
cin >> name;
cin >> age;
```
---
## Standard Error Stream (`cerr`)
The predefined object `cerr` is an instance of the `ostream` class. It is connected to the standard error device, which is also typically the display screen.
Unlike `cout`, the `cerr` object is **unbuffered**. This means that any data inserted into `cerr` is written to the output device immediately, without waiting for a buffer to fill up or be flushed. This ensures that critical error messages are displayed even if the program crashes immediately afterward.
### Example
```cpp
#include
using namespace std;
int main()
{
char str[] = "Unable to read....";
// Outputting an error message immediately
cerr << "Error message : " << str << endl;
return 0;
}
```
### Output
```text
Error message : Unable to read....
```
---
## Standard Log Stream (`clog`)
The predefined object `clog` is also an instance of the `ostream` class and is connected to the standard error device (usually the screen).
However, unlike `cerr`, the `clog` object is **buffered**. This means that characters inserted into `clog` are stored in a buffer and are only written to the output device when the buffer is full, explicitly flushed, or at program termination.
### Example
```cpp
#include
using namespace std;
int main()
{
char str[] = "Unable to read....";
// Logging a message via the buffered log stream
clog << "Error message : " << str << endl;
return 0;
}
```
### Output
```text
Error message : Unable to read....
```
---
## Summary of Differences: `cout`, `cerr`, and `clog`
While the output of `cout`, `cerr`, and `clog` may look identical on your screen in simple console applications, their underlying behaviors and intended use cases differ significantly:
| Stream Object | Stream Type | Buffered? | Primary Purpose | Redirection Behavior |
| :--- | :--- | :--- | :--- | :--- |
| `cout` | Standard Output | Yes | Standard program output (e.g., results, prompts). | Can be easily redirected to a file (e.g., `program > output.txt`). |
| `cerr` | Standard Error | No | Critical error messages that need to be displayed immediately. | Remains visible on the console even if standard output is redirected. |
| `clog` | Standard Error | Yes | Non-critical logging, diagnostics, and execution history. | Useful for high-volume logging where buffering prevents performance bottlenecks. |
### Best Practices
* Use `cout` for standard program output.
* Use `cerr` to display critical errors and diagnostic messages that require immediate visibility.
* Use `clog` for general logging and auditing purposes where performance is a priority.
YouTip