George
George

Reputation: 51

Evaluation of sequence of characters using getchar() and putchar()

#include <stdio.h>
int main()
{
    int c;
    while ((c = getchar()) != EOF) {
        if (c == ' ') {
            while((c = getchar()) == ' ')
                ;
            putchar(' ');
        }
        putchar(c);
    }
    return 0;
}

The above program strips down several consecutive spaces to a single space in a text stream.

I would really appreciate answers to the following questions -

1) If the input is (space space a), does the 1st while test the condition one character at a time?

2)If the 1st while evaluates to true, does the 2nd while condition test using the same character (i.e 1st space) or the 2nd space?

Upvotes: 0

Views: 233

Answers (2)

kocica
kocica

Reputation: 6467

The above program strips down several consecutive spaces to a single space in a text stream.

No it doesnt, this does:

#include <stdio.h>
int main()
{
    int c;
    while ((c = getchar()) != EOF) {
        if (c == ' ') {
            while ((c = getchar()) == ' ');
            if (c == EOF) {
                break;
            }

            putchar(' ');
        }
        putchar(c);
    }
    return 0;
}

Modification:

  • Get printing of (' ') out of the while loop.

1) If the input is (space space a), does the 1st while test the condition one character at a time?

Yes, it will take character, test it in condition, pass it to body if condition is true or skip him if false. Then it will pick next character till c == EOF.

2)If the 1st while evaluates to true, does the 2nd while condition test using the same character (i.e 1st space) or the 2nd space?

No, it will read another character (behind that space) and test it again.

Upvotes: 1

user7345878
user7345878

Reputation: 552

The first while keeps on reading a char until it is an EOF (ctrl + D). The first while will always evaluates to true until you hit EOF.

The second while condition keeps on checking if the input char is a space or not.

Upvotes: 0

Related Questions