Search code examples
cstringgetcharputchar

Removing multiple blanks using putchar and getchar in C


Problem: Write a program that receives textual input using getchar() and outputs the string, having removed multiples blanks.

Here's how I wrote the pseudo-code:

While each input character is received before reaching EOF, do the following:
     1) if character is non-blank, print it out
     2) otherwise:
         a. print out the blank
         b. do nothing untill the next non-blank character 
     3) if a non-blank character is reached, go back to 1)

I tried to implement the algorithm as such:

#include <stdio.h>
/* replaces multiple blanks with a single blank */
main(){
    char c;
    while((c= getchar())!=EOF){
        if (c != ' ')
            putchar(c);
        else {
            putchar(c);
            while(c == ' ')
                ;
        }
    }   
}

When a string contains blanks, it stalls. I am not sure how I should debug it. I think the problem is with my second while, and the program gets into an infinite loop there rather than waiting for the new characters.


Solution

  • #include <stdio.h>
    /* replaces multiple blanks with a single blank */
    main(){
        int c; // thanx chux
        while((c= getchar())!=EOF){
            if (c != ' ')
                putchar(c);
            else {
                putchar(c);
                while((c= getchar())!=EOF)
                    if (c!=' ')
                    {
                        putchar(c);
                        break;
                    }
            }
        }   
    }
    

    Your last while didnt read chars from stdin, causing infinie loop comparing last red character from previous getchar().