Initial Caps

A filter is a program that accepts standard input and generates standard output. These programs are fun to write, providing you have a goal in mind and some way to manipulate the incoming text in a manner that’s significant enough to notice in the output.

For the past five years on this blog, I’ve written several posts on filters:

Lesson – The Caesarian Cipher
Lesson – One Word at a Time
Series – Encoding and Decoding
Lesson – Safe Coding Practices getchar() and putchar()
Lesson – A Word Wrap Filter (Part 1 of 2)
Exercise – The URL Encoding Filter
Exercise – The URL Decoding Filter

It’s time for another!

This idea came to me while I was working on another programming project. I needed to generate text in Title Case, which is also known as Initial Caps. The goal is to capitalize the first letter of each word. I figured it’s a good task for a filter.

For a filter, all input comes from standard input, or the stdin, device. All output is sent to standard output, the stdout device. Both stdin and stdout are defined in C, which means you can use standard I/O or file I/O functions to fetch and put characters.

The following code presents a simple I/O filter that doesn’t modify input:

#include <stdio.h>

int main()
{
    int ch;

    while(1)
    {
        ch = getc(stdin);
        if( ch == EOF)
            break;
        putc(ch,stdout);
    }

    return(0);
}

The while loop between Lines 7 and 13 is an infinite loop, which is typical for a filter. The getc() function at Line 9 fetches a character from standard input, stdin.

At Line 10, the EOF (End of File) condition is checked for. If found, the loop is broken and the program stops. EOF is an integer constant, which is why variable ch is defined as an int, not a char.

Line 12 outputs the same character. In a true filter, like the one you are challenged to create for this Exercise, more action must happen between the if test and putchar().

Using the skeleton provided above (or you can create your own), process input so that the first letter of a word is capitalized and the rest of the characters in the word appear as lower case.

Here are some sample runs to demonstrate what the filter does:

this is all lower case
This Is All Lower Case
THIS IS ALL CAPS
This Is All Caps
This Is Already Initial Caps
This Is Already Initial Caps

The odd-numbered lines (1, 3, and 5) appear as typed. After Enter is pressed, the filter spits out the modified line (lines 2, 4, and 6).

Your task is to write such a filter. It might be trickier than you think, but it can be done! Click here to view my solution, though please try this Exercise on your own before you see how I’ve solved it.

Leave a Reply