Search code examples
cgetchar

limit spaces to only one in text - c


I'm reading through K&R and the question is to: write a program to copy its input to its output, replacing each string of one or more blanks by a single blank. In my mind I think I know what I need to do, set up a boolean to know when I am in a space or not. I've attempted it and did not succeed. I've found this code and it works, I am struggling to figure out what stops the space from being written. I think I may have it but I need clarification.

#include <stdio.h>

int main(void)
{
  int c;
  int inspace;

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

    /* We haven't met 'else' yet, so we have to be a little clumsy */
    if(c != ' ')
    {
      inspace = 0;
      putchar(c);
    }
  }

  return 0;
}

I have created a text file to work on, the text reads:

so this    is where    you have been

After the 's' on 'this' the state changes to 1 because we are in a space. The space gets written and it reads the next space. So now we enter:

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

But inspace is not 0, it is 1. So what happens? Does the code skip to return 0;, not writing anything and just continues the while loop? return 0; is outside of the loop but this is the only way I can see that a value is not returned.


Solution

  • At this point:

    if(c == ' ')
    {
       if(inspace == 0) // <-- here
    

    If inspace is equal to 1, it will not execute the if body, it will jump to:

    if(c != ' ') { 
    

    And as long as c == ' ' above will be false, so it will skip the if body and jump to:

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

    And this will continue until the end of the file or until (c != ' ') evaluates to true. When c is non-space:

     if(c != ' ')
     {
       inspace = 0;
       putchar(c); 
    

    inspace is zeroed, and character is printed.