Exercise 1-8

Write a program to count blanks, tabs, and newlines.

First, we need to be able to read in input. From the examples in the book, you should know by now that we do this by running getchar inside of a while-loop until we read in an EOF. If we want to be able to use the value of getchar, we need to assign it to a variable.

    #include <stdio.h>
    
    main()
    {
        int c;
    
        while ((c = getchar()) != EOF)
            /* code */;
    }

To keep track of how many blanks, tabs, and newlines we come across, we can create variables for each one of them. For every character we read in, we use a series of if-statements that check if the character happens to be a blank, tab, or newline, in which case we increment the corresponding variable. Once we stop reading input, we can print the values of the three variables.

    #include <stdio.h>
    
    main()
    {
        int c, blanks, tabs, lines;
    
        blanks = 0;
        tabs = 0;
        lines = 0;
        while ((c = getchar()) != EOF) {
            if (c == ' ')
                ++blanks;
            if (c == '\t')
                ++tabs;
            if (c == '\n')
                ++lines;
        }
        printf("blanks: %d, tabs: %d, lines: %d\n", blanks, tabs, lines);
    }

Note: for now, there are two ways to pass input into your programs. You can enter input through the terminal, but for this program and many of the ones coming up, it may be more convenient to cat a file with the input and pipe its output into your program (cat /path/to/file | /path/to/exec.) The equivalent command in Windows is type C:\\path\to\file | C:\\path\to\exec.exe. Later, we will learn how to get our programs to read from files directly.