cgetcharputchar

Replace each string of one or more blanks with a single blank


This was already asked, but I made my own program and I don't know why it doesn't work.

int c;
char blank;


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

Basically, replace space with nothing is what I did. But it doesn't work. If I put '1' instead of '' it replaces spaces with 1s so I don't know what's the problem


Solution

  • The specific error in your code is in the way you have used the putchar() function. When using putchar() you must put a character inside, such as putchar('a'), but you cannot leave it empty. This is why you are receiving the error:

    error: empty character constant

    Basically, putchar() must put a character and whatever is in between the single quotes: '', is not a character.

    To fix your code: you should remove the putchar('') line entirely, so your code would looks like this:

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