ARich ARich - 3 months ago 26
C Question

Space isn't replaced

I'm learning by reading K&R. I'm trying to be methodical and make sure I understand the concepts before moving on.

One of the exercises asks to write a program that copies the input to the output "replacing each string of one or more blanks with one blank."

I have written the following, but it outputs the input verbatim even when multiple consecutive blanks exist:

#include <stdio.h>

main()

{
int c, d, a;

c = getchar();
while (c != EOF)
{
a = c;

if (c == ' ' && d == ' ')
{
a = 0;
}

d = c;

putchar(a);
c = getchar();
}
}


What am I doing wrong here? I'm not very far into the book, so I feel like I'm missing something really simple...

Answer

There are some good points in the comments:

  • use meaningful variable names
  • putchar(0) is not the same as not writing anything
  • all variables need to be initialized

I would make one more suggestion:

  • the while loop should read the character and check for EOF as shown below

(Assuming that you have the 2nd edition of K&R, see section 1.5.1 on page 17 for a detailed explanation.)

Here's how I would write the code:

#include <stdio.h>

int main(void)
{
    int c;
    int oldc = 'a';

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