Search code examples
ckernighan-and-ritchie

K&R Exercise 1-20 The Programming Language 2nd edition


What should i do in this program. I cant understand.
The question is as : 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?
I started by replacing the tabs ('\t') with space (' '). But i guess this is the wrong approach. please suggest ?
and btw what should n be? variable or symbolic parameter?

code so far:

#include<stdio.h>
#define TAB 5
int main() {
    int i, c;
    while((c = getchar()) != EOF) {
        if(c == '\t') {
            for(i = 0; i < TAB; ++i)
                putchar(' ');
        } else
            putchar(c);
    }
    return 0;
}

In all the questions posted for this exercise i couldn't understand the meaning.


This is my final code, please tell me if it has any problems / bugs. I think it is working as it should..
thanks to @Nit, @Chrono Kitsune , @dasblinkenlight and all the others who helped.

#include<stdio.h>
#define TAB 8
int main() {
int c, count = 0, space = 0;
while((c = getchar()) != EOF) {

    if(c == '\t') {
        space = (TAB - (count % TAB));
        while(space > 0){
            putchar(' ');
            count++;
            space--;
        }
    }
    else{
        putchar(c);
        ++count;
    }

    if(c == '\n')
        count = 0;
}
return 0;
}

Solution

  • What you are doing is not what the exercise wants you to do: rather than inserting a fixed number of spaces for each tab, you should be inserting a different number of spaces depending on how much has been printed on the line so far.

    It does not matter how you take the number of spaces per tab - the way you made it a preprocessor constant is perfectly fine. However, rather than producing TAB spaces regardless of where the '\t' has been found, you program needs to count how much "regular" characters have been printed, and count how many spaces are needed when it sees '\t'.

    Make a variable count for characters printed so far. Initialize it to zero, and then reset it back to zero each time you see a '\n' character. When you call putchar, also make count++.

    Now when you see a tab '\t' compute how far you are form the next tab stop. The expression for that is

    TAB - (count % TAB)
    

    That is how many spaces you need to print.

    This should be enough information for you to go back and fix your program - I think you need to write only five additional lines of code (not counting lines for curly braces that you would need to insert) in order to finish this exercise.