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.

#include <iostream>
#include <string>
#include <algorithm>

int main() {
    std::string line;

    // Read input line by line
    while (std::getline(std::cin, line)) {
        // Convert the line to uppercase
        std::transform(line.begin(), line.end(), line.begin(), ::toupper);

        // Write out the uppercased line
        std::cout << line << std::endl;
    }

    // Check for errors during input
    if (std::cin.bad()) {
        std::cerr << "error: I/O error occurred" << std::endl;
        return 1;
    }

    return 0;
}

In this C++ version:

  1. We use std::getline() to read input line by line from std::cin.

  2. The std::transform() function is used along with the ::toupper function to convert each line to uppercase.

  3. We print the uppercased line using std::cout.

  4. 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.

$ echo 'hello'   > /tmp/lines
$ echo 'filter' >> /tmp/lines

Then compile and use the line filter to get uppercase lines.

$ g++ -o line_filter line_filter.cpp
$ cat /tmp/lines | ./line_filter
HELLO
FILTER

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.