In C++, an input stream is a fundamental mechanism for reading data from various sources such as files, console, or network. The standard input stream (std::cin
) is part of the C++ Standard Input/Output Library, which allows programmers to read different types of data efficiently.
Stream Types in C++
C++ provides several stream types for input operations:
Stream Type |
Description |
Header |
istream |
Base input stream class |
<iostream> |
ifstream |
Input file stream |
<fstream> |
istringstream |
Input string stream |
<sstream> |
graph LR
A[Input Source] --> B[Stream Buffer]
B --> C[Extraction Operator >>]
C --> D[Program Variables]
Reading Different Data Types
#include <iostream>
#include <string>
int main() {
int number;
std::string text;
double decimal;
// Reading different data types
std::cin >> number; // Integer input
std::cin >> text; // String input
std::cin >> decimal; // Floating-point input
return 0;
}
Stream State Flags
Streams maintain internal state flags to track reading operations:
good()
: Stream is ready for operations
fail()
: Last input operation failed
eof()
: End of input reached
bad()
: Critical stream error
#include <iostream>
#include <limits>
int main() {
int value;
// Check input validity
while (!(std::cin >> value)) {
std::cin.clear(); // Clear error flags
std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
std::cout << "Invalid input. Try again.\n";
}
return 0;
}
Stream Buffer Concepts
Input streams use a buffer to temporarily store incoming data, improving reading performance by reducing direct system calls.
LabEx Practical Tip
When learning input streams, practice is key. LabEx recommends creating small programs to experiment with different input scenarios and stream manipulations.