Cpp Libs Iostream
# C++ Standard Input/Output: ``
The `` library is a fundamental header in the C++ Standard Library used for input and output (I/O) operations. It defines several stream classes, objects, and operators that allow your program to interact with standard input/output devices, such as the keyboard and the screen.
---
## Core Classes and Stream Objects
The `` library is built on a hierarchy of stream classes. The most important classes and pre-defined stream objects include:
### Core Classes
* `std::istream`: An abstract base class designed for input operations.
* `std::ostream`: An abstract base class designed for output operations.
* `std::iostream`: A class derived from both `std::istream` and `std::ostream`, supporting bidirectional input and output operations.
### Pre-defined Stream Objects
* `std::cin`: The standard input stream, typically associated with the keyboard.
* `std::cout`: The standard output stream, typically associated with the screen (buffered).
* `std::cerr`: The standard error output stream, typically associated with the screen. It is **unbuffered**, meaning messages are printed immediately.
* `std::clog`: The standard log stream, typically associated with the screen. It is **buffered**, making it more efficient for non-critical logging.
---
## Stream Operators
C++ uses overloaded operators to perform stream insertion and extraction:
* `>>` (Extraction Operator): Used to read formatted data from an input stream (e.g., `std::cin >> variable;`).
* `<<` (Insertion Operator): Used to write formatted data to an output stream (e.g., `std::cout << variable;`).
---
## Code Examples and Practical Usage
### 1. Standard Input and Output
This example demonstrates how to prompt a user for input using `std::cout` and read their response using `std::cin`.
```cpp
#include
#include
int main() {
int age;
std::string name;
// Use std::cout to print to the screen
std::cout << "Enter your name: ";
// Use std::cin to read input from the keyboard
std::cin >> name;
std::cout << "Enter your age: ";
std::cin >> age;
// Output the retrieved data
std::cout << "Hello, " << name << "! You are " << age << " years old." << std::endl;
return 0;
}
```
### 2. Standard Error Output (`std::cerr`)
Use `std::cerr` to output error messages. Because it is unbuffered, it guarantees that the message is displayed immediately, even if the program crashes shortly after.
```cpp
#include
int main() {
// Output an error message immediately to the standard error stream
std::cerr << "An error occurred!" << std::endl;
return 0;
}
```
### 3. Standard Log Output (`std::clog`)
Use `std::clog` for non-critical logging. Because it is buffered, it is more performant than `std::cerr` for frequent logging operations.
```cpp
#include
int main() {
// Output a log message to the standard log stream
std::clog << "This is a log message." << std::endl;
return 0;
}
```
### 4. Formatted Output with ``
To format your output (such as setting decimal precision, field width, or alignment), you can combine `` with the `` library.
```cpp
#include
#include
int main() {
double pi = 3.14159;
// Set output precision (total significant digits)
std::cout << std::setprecision(3) << pi << std::endl; // Outputs: 3.14
// Set output width and alignment
std::cout << std::setw(10) << std::left << pi << std::endl; // Left-aligned in a 10-character field
std::cout << std::setw(10) << std::right << pi << std::endl; // Right-aligned in a 10-character field
return 0;
}
```
### 5. Checking Stream States
You can check the state of an input stream to verify if the last read operation succeeded. This is crucial for handling invalid user input.
```cpp
#include
int main() {
int num;
std::cout << "Enter a number: ";
std::cin >> num;
// Check if the input operation failed (e.g., if the user entered a letter instead of a number)
if (std::cin.fail()) {
std::cerr << "Invalid input! Not an integer." << std::endl;
} else {
std::cout << "You entered: " << num << std::endl;
}
return 0;
}
```
### 6. Handling Strings with Spaces
The standard extraction operator `>>` stops reading when it encounters whitespace. To read an entire line of text (including spaces), use `std::getline`.
```cpp
#include
#include
int main() {
std::string fullName;
std::cout << "Enter your full name: ";
// Read the entire line of input, including spaces
std::getline(std::cin, fullName);
std::cout << "Hello, " << fullName << "!" << std::endl;
return 0;
}
```
---
## Key Considerations
1. **`std::endl` vs `\n`**:
* `std::endl` inserts a newline character (`\n`) and forces the output buffer to flush.
* Using `\n` only inserts a newline without flushing. For high-performance console output, prefer `\n` to avoid unnecessary flushing overhead.
2. **Buffer Synchronization**: By default, C++ standard streams synchronize their buffers with the standard C library streams (`stdio`). If your program relies heavily on standard C++ streams and does not use C-style I/O (`printf`/`scanf`), you can speed up execution by disabling synchronization at the start of your `main` function:
```cpp
std::ios_base::sync_with_stdio(false);
std::cin.tie(NULL);
```
3. **Stream Failures**: Always validate user input. If `std::cin` enters a fail state (e.g., when expecting an integer but receiving a string), subsequent input operations will fail silently until you call `std::cin.clear()` and discard the invalid characters in the buffer.
YouTip