Stripping Blanks in C

I’ve now spent 2 days of 100DaysOfCode struggling with this seemingly simple problem from K & R C. I am ready to ask for help :slight_smile:

The problem:

Write a program to copy its input to its output, replacing each string of one or more blanks by a single blank.

What I have tried:

Many things, my most recent code looks like this.

#include <stdio.h>

int main()
{
    int c, d;

    while ((c = getchar()) != EOF)
    {
        if (c != ' ')
        {
            // printf("Not Blank\n");
            putchar(c);
        }
        else
        {
            putchar(c);
            //printf("Blank\n");

            while ((c = getchar()) == ' ')
            {
                //printf("Next is Blank\n");
                putchar(c);
                putchar('\b');
            }
        }
    }
}

The biggest issue is that although it does strip out multiple spaces it also seems to take out the first letter of every word after the first word.

hello world
hello orld
hello world its me lev
hello orld ts e ev
hello         world
hello orld

Could someone point me in the right direction without just giving me the answer?

In your inner while loop, you should not be outputting anything. Wait till it is over and output c, because you know it will not be a space.

1 Like

Or you could just use the standard library (stdio.h) scanf family of functions. It supports whitespace suppression and doesn’t care if the input doesn’t match all the specifiers. Meaning you could use a hack like

char *p;
int n = scanf(" %s %s %s %s %s %s %s %s %s %s %s %s %s %s %s %s %s %s %s %s %s ", &p);
if (n > 0) {
    printf("%s\n", p);
} else { // error handling
1 Like

Thanks, if I do nothing in the while loop the same thing happens :confused:

#include <stdio.h>

int main()
{
    int c;

    while ((c = getchar()) != EOF)
    {
        if (c != ' ')
        {
            putchar(c);
        }
        else
        {
            putchar(c);
            while ((c = getchar()) == ' ')
            {
            }
        }
    }
}

output:

Levs-iMac:ch1 levlaz$ ./a.out
hello
hello

hello world
hello orld
hello     world
hello orld

Thanks for the tip but the purpose of this exercise was to do it without any additional libraries or functions outside of the ones that we covered so far.

Namely, putchar() and getchar()

I figured it out, I am still not sure why but the order of my if statement was causing the issue.

The working code looks like this:

#include <stdio.h>

int main()
{
    int c;

    while ((c = getchar()) != EOF)
    {
        if (c == ' ')
        {
            putchar(c);
            while ((c = getchar()) == ' ')
            {

            }
        }

        putchar(c);
    }
}
Levs-iMac:ch1 levlaz$ ./a.out
thank you randell
thank you randell
THANK YOU     RANDELL     !!!
THANK YOU RANDELL !!!

:smiley:

It wasn’t the order, you just weren’t printing the char before.