Stream processing handles data as a sequence flowing through a program. In C++, stream operators move typed values between a program and an input or output source; ranges and views process container sequences with less loop housekeeping. section 6.1 section 4.4
Two practical uses show why streams help:
- Replace scanf and printf format strings, which can mismatch data types and cause undefined behavior, with extraction (>>) and insertion (<<) operators. Check each extraction: inconsistent input can still fail, but separate checks give finer-grained error detection. section 6.1
- Process container values with ranges and views instead of repeated loops and a temporary vector. A transform can take absolute values, a filter can keep even values, and accumulate can sum them. 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 typed extraction and individual failure checks with format-string input. The example also illustrates why correct conversions do not guarantee correct output. 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 sequence transformed and filtered through views, then summed with accumulate. section 4.4



















