C 将输入复制到输出,对于包含一个或多个空格的字符串,输出一个空格

C 将输入复制到输出,对于包含一个或多个空格的字符串,输出一个空格,c,input,implementation,C,Input,Implementation,问题就在这里 比如说 in = "a b\nab c\ndd"; out = "a b\nb c\ndd" Here is my C code while(c=getchar()!=EOF){ if(c==' '){ while( (c1=getchar()) == ' '); // ignore all other contiguous blank putchar(c); // output one blank putchar(c1); //

问题就在这里 比如说

in = "a    b\nab  c\ndd";
out = "a b\nb c\ndd"
Here is my C code

while(c=getchar()!=EOF){
  if(c==' '){
      while( (c1=getchar()) == ' '); // ignore all other contiguous blank
      putchar(c); // output one blank
      putchar(c1);  // output the next non-blank character             
  }
  else putchar(c);
}

我可以有一个缩小尺寸的实现吗

假设您只删除

int c;
char space_found = 0;

while ( ( c = getchar() ) != EOF) {
   if ( (!space_found) || (c != ' ') ) { // if the previous is not a space, or this is not a space
       putchar(c);
   }
   space_found = (c == ' '); // (un)set the flag
}
您可以通过一个简单的宏将其更改为检查任何空白:

#define is_white_space(X) ( ( (X) == ' ' ) || ( (X) == '\t' ) || ( (X) == '\n' ) )

并用它替换
c='

如果你不介意人为地限制“单词”的大小,那么很容易将其缩短一点:

// pick your limit here:
char word[256];

// and be sure the length here matches:
while (scanf("%255s", buffer))
    printf(" %s", buffer);
  • 尝试读取一个字符
  • 如果输入缓冲区不为空,则输出先前读取的字符。否则,跳到步骤6
  • 如果先前读取的字符是空格,则继续获取字符,直到收到非空格字符
  • 如果输入缓冲区不为空,则输出最近读取的字符
  • 转到步骤1
  • 最终实现
  • 示例实现:

    while ((c = getchar ()) != EOF)
      {
        putchar (c);
        if (c == ' ')
          {
            while ((c = getchar ()) == ' ')
              {}
            if (c != EOF)
              {
                putchar (c);
              }
          }
      }
    

    在输出示例中,我认为您缺少第二行的
    a
    (因此应该是
    a b\nab c\ndd