Line Filters in C++
A line filter is a common type of program that reads input on stdin, processes it, and then prints some derived result to stdout. grep
and sed
are common line filters.
Here’s an example line filter in C++ that writes a capitalized version of all input text. You can use this pattern to write your own C++ line filters.
In this C++ version:
We use
std::getline()
to read input line by line fromstd::cin
.The
std::transform()
function is used along with the::toupper
function to convert each line to uppercase.We print the uppercased line using
std::cout
.After the loop, we check for I/O errors using
std::cin.bad()
.
To try out our line filter, first make a file with a few lowercase lines.
Then compile and use the line filter to get uppercase lines.
This C++ version achieves the same functionality as the original code, reading input line by line, converting each line to uppercase, and writing the result to stdout.