0

I have this simple program:

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

            if (c == EOF) break;
        }

        putchar(c);
    }
}

As I understand it, there are two loops. The condition for the first loop is for the output of getchar to be different then EOF (so implicitly the loop breaks at EOF); the condition for the second loop is that the output of getchar is not blank, then it'll output exactly one blank and if by any chance the non-blank character was EOF the whole program will interrupt.

Is it necessary to place a second check for EOF? Wouldn't it be "spotted" by the condition of the first loop?

How comes that the blank characters will be "consumed" by the second loop, but the first non-blank character is still there for the first getchar to be read?

Jodrell
  • 34,946
  • 5
  • 87
  • 124
maja
  • 697
  • 5
  • 18
  • for example if I input the string "this example", the getchar in the outer loop would read the first blank, then the getchar in the inner loop would read a blank and the letter "e", then how comes that the letter "e" will be read also by the other getchar once the inner loop breaks? – maja Jan 29 '15 at 09:22
  • after reasoning on the answer for the need of a break I guess that the putchar on the outer loop outputs the character read by the getchar in the inner loop... – maja Jan 29 '15 at 09:23
  • yes to the second comment. – Jodrell Jan 29 '15 at 09:26

1 Answers1

1

Okay,

The inner

if (c == EOF) break;

avoids the subsequent

putchar(c);

which would otherwise be performed if that cycle of the loop was completed.


e.g.

main()
{
    int c;
    while ((c = getchar()) != EOF)
    {
        if (c == ' ')
        {
            while ((c = getchar()) == ' ');
            putchar(' ');
            if (c == EOF) break; // <<- This ...
        }

        putchar(c);             // <<- ... jumps past this.
    }
}
Jodrell
  • 34,946
  • 5
  • 87
  • 124
  • @maja, well, its a matter a style and subjective but I think it makes it easier to see the flow. – Jodrell Jan 29 '15 at 09:19
  • the second thing you wrote was the starting program, the exercise (I'm following a textbook) was to have the progra output only a single blank for any string of consecutive blanks in the input. – maja Jan 29 '15 at 10:54
  • notice that the inner loop's getchar is followed by a `;` , that makes so that any "extra" white spaces will just be skipped until a different character is found. – maja Jan 29 '15 at 10:55