HiveBrain v1.2.0
Get Started
← Back to all entries
patterncMinor

K&R Exercise 1-20: tabs to spaces

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
tabsspacesexercise

Problem

I'm learning C with K&R 2nd Ed. I've just completed the exercise 1-20 and I would know if my code is correct (i.e. answering the question) and if my style is not too bad. Or just some feebacks to improve myself!


K&R Exercise 1-20 p.34


Write a program detab that replaces tabs in the input with the proper number * of blanks to space to the next tab stop. Assume a fixed set of tab stops, say every n
columns. Should n be a variable or a symbolic parameter?

More info here

I put '-' because it's more readable than ' '. But you can totally change it.

#include 
#define COLUMN 8

int main()
{
    int c, i, nc;
    nc = 0;

    while ((c = getchar()) != EOF)
    {
        if (c != '\t' && c != '\n')
            nc = (nc + 1) % COLUMN;

        if (c == '\n')
            nc = 0;

        if (c == '\t') {
            for (i=1; i<=(COLUMN - nc); ++i) {
                putchar('-');
            }
            nc = 0;
        }
        else
            putchar(c);
    }

return(0);
}

Solution

Here is an alternate algorithm:

while ((c = getchar()) != EOF) {
    switch (c) {/* switch instead of if-else... */
    case '\n':
        nc = 0;
        putchar(c);
        break;
    case '\t':
        for (i = COLUMN - nc % COLUMN, nc += i; i > 0; --i) {
            putchar('-');
        }
        break;
    default:
        ++nc; /* increment is faster than increment plus divide */
        putchar(c);
        break;
    }
}


nc keeps track of the current column position within the line.

Code Snippets

while ((c = getchar()) != EOF) {
    switch (c) {/* switch instead of if-else... */
    case '\n':
        nc = 0;
        putchar(c);
        break;
    case '\t':
        for (i = COLUMN - nc % COLUMN, nc += i; i > 0; --i) {
            putchar('-');
        }
        break;
    default:
        ++nc; /* increment is faster than increment plus divide */
        putchar(c);
        break;
    }
}

Context

StackExchange Code Review Q#80426, answer score: 2

Revisions (0)

No revisions yet.