ckernighan-and-ritchie

Program to remove trailing blanks not working


Recently I've been working on an exercise from K & R's C book, which states: write a program to remove trailing blanks/ tabs from each line of input.

I've tried A LOT of ways using functions and didn't work. So I decided to put everything inside main() and it just doesn't work either!

Here's the code:

#include <stdio.h>
#define MAX_INPUT 100
#define ACTIVE 1 //quit with Ctrl + C

void main(){
    int i, nb, nt;
    char c;
    char line[MAX_INPUT];
    char corrected[MAX_INPUT];  

    while(ACTIVE){
        //get current line
        for(i = 0; i < MAX_INPUT - 1 && (c = getchar()) != EOF && c != '\n'; i++)
            line[i] = c;
        if(c == '\n'){
            line[i] = c;
        }
        line[i + 1] = '\0';

        //correct current line
        nb = nt = 0;
        for(i = 0; line[i] != '\0'; i++){
            if(line[i] == ' '){
                nb++;
                if(nb == 1)
                    corrected[i] == line[i];
            }

            else{
                if(line[i] == '\t'){
                    nt++;
                    if(nt == 1)
                        corrected[i] == line[i];
                }

                else
                    corrected[i] == line[i];
            }
        }
        corrected[i] == '\n';
        corrected[i + 1] == '\0';

        //print corrected line
        printf("%s", corrected);    
    }
}

So, by the time I want to print the "corrected" version of the current line, it prints this instead:

I'd really appreciate the help. I've been trying this the whole week and it's driving me crazy the fact I can't find the error. Thanks for your attention, folks!


Solution

  • Change

    corrected[i] == line[i];
    corrected[i] == '\n';
    corrected[i + 1] == '\0';
    

    to

    corrected[i] = line[i];
    corrected[i] = '\n';
    corrected[i + 1] = '\0';
    

    == is an equality operator, while = is an assignment operator.