C程序,新行和制表符彼此相邻的问题

Mat*_*012 3 c

这是我的原始代码:

#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;
}
Run Code Online (Sandbox Code Playgroud)

但问题是如果有多个空格(空格)或多个标签彼此相邻,则会为两者打印换行符.所以我使用变量(last)来跟踪我的位置:

#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;
}
Run Code Online (Sandbox Code Playgroud)

这解决了它,除非现在彼此相邻[空白] [tab],否则会打印换行符.

有人可以帮忙吗?

pax*_*blo 6

您原始代码的问题在于您将为每个空白字符输出换行符.您只想在从单词转换为非单词时执行此操作:

更改:

if (c == ' ' || c == '\n' || c == '\t') {
    state = OUT;
    printf("\n");
}
Run Code Online (Sandbox Code Playgroud)

至:

if (c == ' ' || c == '\n' || c == '\t') {
    if (state == IN) printf("\n");
    state = OUT;
}
Run Code Online (Sandbox Code Playgroud)

事实上,我原先认为我建议的是对各州的列举:

enum eState {IN, OUT};
:
enum eState state = OUT;
Run Code Online (Sandbox Code Playgroud)

但是,对于只有两个状态的简单有限状态机,您可以使用布尔值:

#include <stdio.h>

#define FALSE (1==0)
#define TRUE  (1==1)
// Or: enum eBoolean {FALSE = 0, TRUE = 1};

int main (void) {
    int ch;
    int inWord = FALSE;     // Or: enum eBoolean inWord = FALSE;

    // Process every character.
    while ((ch = getchar()) != EOF) {
        // Check for whitespace.
        if (ch == ' ' || ch == '\n' || ch == '\t') {
            // Check if transitioning nonwhite to white.
            if (inWord) {
                printf("\n");
            }

            // Mark white no matter what.
            inWord = FALSE;
        } else {
            // Mark non whitespace.
            inWord = TRUE;
        }

        // If not whitespace, output character.
        if (inWord) {
            putchar(ch);
        }
    }
    return 0;
}
Run Code Online (Sandbox Code Playgroud)