Here was my original code:
#include <stdio.h>
#define IN 1 // inside a word
#define OUT 0 // outside a word
// program to print input one word per line
int main(void)
{
int c, state;
state = OUT;
while ((c = getchar()) != EOF) {
if (c == ' ' || c == '\n' || c == '\t') {
state = OUT;
printf("\n");
}
else if (state == OUT) {
state = IN;
}
if (state == IN) {
putchar(c);
}
}
return 0;
}
But the problem was if there were multiple blanks (spaces) or multiple tabs next to each other a newline would be printed for both. So I used a variable (last) to keep track of where I was:
#include <stdio.h>
#define IN 1 // inside a word
#define OUT 0 // outside a word
// program to print input one word per line, corrected bug if there was
// more than one space between words to only print one \n
int main(void)
{
int c, last, state;
last = EOF;
state = OUT;
while ((c = getchar()) != EOF) {
if (c == ' ' || c == '\n' || c == '\t') {
if (last != c) {
state = OUT;
printf("\n");
}
}
else if (state == OUT) {
state = IN;
}
if (state == IN) {
putchar(c);
}
last = c;
}
return 0;
}
That solved it, except now if there is [blank][tab] next to each other, a newline gets printed for both.
Could someone please help?