MW2000 MW2000 - 1 year ago 73
C Question

K&R Exercise 1-9 (C)

"Write a program to copy its input to
its output, replacing each string of
one or more blanks by a single blank."

I'm assuming by this he means input something like...


... and output it like:


This is probably easier than I'm making it out to be, but still, I can't seem to figure it out. I don't really want the code... more so pseudo code.

Also, how should I be looking at this? I'm pretty sure whatever program I write is going to need at least one
, a
loop, a couple
statements, and will use both the
functions... but besides that I'm at a loss. I don't really have a programmers train of thought yet, so if you could give me some advice as to how I should be looking at "problems" in general that'd be awesome.

(And please don't bring up
, I haven't got that far in the book so right now that's out of my scope.)

Answer Source

Pseudo code

while c = getchar:
    if c is blank:
        c = getchar until c is not blank
        print blank
    print c


You can substitute use of isblank here if you desire. It is unspecified what characters contrive blank, or what blank value is to be printed in place of others.

After many points made by Matthew in the comments below, this version, and the one containing isblank are the same.

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