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

标签 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;
}

但问题是如果有多个空格(空格)或多个制表符彼此相邻,则会为两者打印换行符。所以我使用了一个变量(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;
}

那解决了它,除了现在如果 [blank][tab] 彼此相邻,则会为两者打印一个换行符。

有人可以帮忙吗?

最佳答案

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

改变:

if (c == ' ' || c == '\n' || c == '\t') {
    state = OUT;
    printf("\n");
}

到:

if (c == ' ' || c == '\n' || c == '\t') {
    if (state == IN) printf("\n");
    state = OUT;
}

事实上,我最初认为我建议的是按照以下方式对各州进行枚举:

enum eState {IN, OUT};
:
enum eState state = OUT;

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

#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;
}

关于C程序,换行符和制表符彼此相邻的问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3974416/

相关文章:

c - iptables 的队列处理程序 : Why does it stuck during receive ICMP packets?

c - 为什么 *s 和 *s++ 在以下情况下具有相同的值?

c++ - 我可以使用 C/C++ 预处理器添加数字吗?

c - 无法通过cmd2运行c程序

c - 我正在使用 Turbo C++,但我的程序没有产生任何输出

c - 太多打开的文件c

c++ - 在循环中声明变量是否有效?

c - 为什么 x - y 在这个函数中不会溢出 TMin?为什么在这种情况下功能错误?

c - 如何在C中逐行读取HTTP文件

c - 分析C程序的内存使用情况