A data stream represents a sequential flow between a C++ program and an input or output source. Prefer streams when moving character data: insertion (<<) and extraction (>>) operators use the destination type to guide conversion, avoiding fragile format specifiers. section 6.1
A common mistake is treating scanf and printf as interchangeable with C++ streams. Their format strings are not type-safe, mismatches can cause undefined behavior, and recovery must infer which conversion failed. Stream operations allow each extraction to be checked separately through the stream's failure state. section 6.1
Use the stream model to keep conversions and sequence processing explicit:
- Extract values one at a time and test failure after each operation when input may be inconsistent. section 6.1
- Configure the input base when the data requires it; for example, set base 8 before reading octal data. section 6.1
- Treat containers as data sequences that can be processed as streams, then compose transformations, filters, and reductions where readability remains clear. section 4.4
Listing 6.2 Using types to determine conversions
int main() {
std::istringstream str("3.14159 042 boxes .3");
double pi;
int cats;
int mice;
std::string buffer;
str >> pi; #1
if (str.fail())
std::cout << "error reading value 1\n";
str >> cats;
if (str.fail())
std::cout << "error reading value 2\n";
str >> buffer;
if (str.fail())
std::cout << "error reading value 3\n";
str >> mice;
if (str.fail())
std::cout << "error reading value 4\n";
std::cout << pi << " being eaten by " << cats << " cats in " << mice
<< " along with " << mice << " mice\n"; #2
return 0;
}
Compare type-directed extraction with format-string conversion and inspect separate failure checks for each value. section 6.1
Listing 4.9 Composed functions on a value sequence
int main() {
std::vector<int> vals { 42, 3, 7 -9, 0, 22, 23, -7, 22 };
auto evens = vals
| std::views::transform([](int x) { return abs(x); })
| std::views::filter([](int x){ return x % 2 == 0; }); #1
auto sum = std::accumulate(evens.begin(), evens.end(), 0); #2
std::cout << sum << '\n';
return 0;
}
See a value sequence transformed, filtered, and reduced through composed range operations. section 4.4


















