首页 > 解决方案 > C中的空间缩减

问题描述

我有一个任务说'重写输入的文本并将多个空格减少到只有一个空格'。我编写的程序会重写单个单词,但在我输入一个空格后完全停止工作。

 #include <stdio.h>
int main()
{
    int t,c,state;
    state=1;
    while((c=getchar())!=EOF)
    {
        if(c==' ') 
            state=0;
        if (state==0)
        {
            while(c=' ')
                state=0;
            putchar(' ');
            putchar(c);
            state=1;
        }
        else putchar(c);
    }
}

标签: c

解决方案


你的代码是错误的。您试图制造一台基本上是正确方法的 staet 机器,但您失败了,因为这些行存在两个问题:

while(c=' ')
  state=0;

首先你肯定想写while(c == ' '),你的编译器可能警告过你。

但即使这是错误的:

while(c == ' ')
  state=0;

如果条件c == ' '为真,此循环将永远不会结束。

你需要的是这样的:

#include <stdio.h>

int main(void) {
  int c;
  int spaceread = 1;

  while ((c = getchar()) != EOF) {
    if (c != ' ')
      spaceread = 0;   // something else than space => process normally
    else
    {
      // space char has been read

      if (spaceread)   // if a space has been read previously => do nothing,
        continue;      // just continue to read the next character.

      spaceread = 1;   // remember we've read a space
    }

    putchar(c);        // print character
  }
}

推荐阅读