To copy the input to the output, we print every character using
putchar
after reading it in with getchar
.
#include <stdio.h>
main()
{
int c;
while ((c = getchar()) != EOF)
putchar(c);
}
In order to detect a sequence of blanks, we need to keep track of
whether the previous character was a blank. We can do this by creating
the variable prev, which we set to the symbolic
constant BLANK
after a blank is read in and printed, and
to the constant NOTBLANK
after a non-blank character is
read in and printed. We make it so that we only print blanks when
prev is equal to NOTBLANK
. prev will
be NOTBLANK
when we come across the first blank, so it
gets printed, but any subsequent blanks will get skipped.
#include <stdio.h>
#define BLANK 1 /* previous character was a blank */
#define NOTBLANK 0 /* previous character was not a blank */
main()
{
int c;
int prev; /* whether the previous character was a blank */
prev = NOTBLANK;
while ((c = getchar()) != EOF) {
if (prev == NOTBLANK) {
if (c == ' ') {
putchar(c);
prev = BLANK;
}
if (c == '\t') {
putchar(c);
prev = BLANK;
}
}
if (c != ' ') {
if (c != '\t') {
putchar(c);
prev = NOTBLANK;
}
}
}
}