Exercise 1-18 in K&R The C Programming Language

1.6k views Asked by At

This exercise is driving me crazy. Sorry if my programming problems seem petty, but I'm a beginner so please bear with me.

The exercise asks for the following: Write a program to remove trailing blanks and tabs from each line of input, and to delete entirely blank lines.

Can anybody tell me why my code doesn't work? I haven't yet tackled the issue of entirely blank lines, but I can't find any reason why my code won't remove trailing blanks and tabs. Here it is:

#include <stdio.h>

#define MAXLINE 1000

int better_line_length(char line[], int lim);
void copy(char to[], char from[]);

int main(void)
{
    int len;
    char s[MAXLINE];
    char better_s[MAXLINE];

    while ((len = better_line_length(s, MAXLINE)) > 0) {
        copy(better_s, s);
        printf("%s\n", better_s); 
    }

    return 0;
}

int better_line_length(char s[], int lim)
{
    int c, i, last_letter;

    for (i = 0; i < lim - 1 && (c = getchar()) != EOF && c != '\n'; ++i) {
        s[i] = c;
        if (c != ' ' && c != '\t')
            last_letter = i;
    }

    s[last_letter+1] = '\0';

    return last_letter+1;
}

void copy(char to[], char from[]) 
{
    int i = 0;

    while ((to[i] = from[i]) != '\0')
        ++i;
}

For example, I expect the code to work as follows: If my input is like this (where '▯' indicates a space):

abcdefg▯▯▯▯▯▯▯▯▯▯▯▯

I expect the output to be

abcdefg

Notice that there are no spaces after the expected output.

But instead, the output I get is an infinite printing of the first character of the input.

UPDATE: My code works as expected when input is taken from the keyboard, but I still get the repeating of one character when input is taken from another file. My mind is blown.

1

There are 1 answers

2
syntagma On BEST ANSWER

The problem is this part of your code:

while ((len = better_line_length(s, MAXLINE)) > 0) {
    copy(better_s, s);
    printf("%s\n", better_s); 
}

It iterates infinitely as the result of (len = better_line_length(s, MAXLINE)) will always be greater than 0 (for strings with at least 1 character).

You do not need a while loop. Instead, do it like this:

len = better_line_length(s, MAXLINE);
copy(better_s, s);
printf("%s|\n", better_s); 

(also note that you don't use len anywhere)