C程序设计语言习题—1

来源:互联网 发布:重生之星际淘宝主yoyo 编辑:程序博客网 时间:2024/04/30 16:00

习题1.8 Write a program to copy its input to its output, replacing each string of one or more blanks by a single blank.

   (编写一个程序,把它的输入复制到输出,并在此过程中将相邻的空格使用一个空格代替)

解题思路:

    1.复制输入到输出使用getchar()/putchar()实现

    2.空格替代,使用一个标识符记录空格是否连续出现。

代码:

#include "stdio.h"

void main()
{
    int c;
    bool flag = true;
    while ((c = getchar()) != EOF)
    {
        if (c != ' ')
        {
            putchar(c);
            flag = true;
        }
        else if(c == ' ' && flag == true)
        {
            putchar(c);
            flag = false;
        }
    }
}

 

附答案版:

#include <stdio.h>

int main(void)
{
  int c;
  int inspace;

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

    /* We haven't met 'else' yet, so we have to be a little clumsy */
    if(c != ' ')
    {
      inspace = 0;
      putchar(c);
    }
  }

  return 0;
}

 

原创粉丝点击