首页 > 其他 > 详细

c程序设计语言_习题1-9_将输入流复制到输出流,并将多个空格过滤成一个空格

时间:2014-04-07 11:30:03      阅读:525      评论:0      收藏:0      [点我收藏+]

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

  编写这样一个程序,实现将输入流复制到输出流,但是要将输入流中多个空格过滤成一个空格。 


1.旗帜变量方法

bubuko.com,布布扣
#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; }
bubuko.com,布布扣


2.保存上一个输入字符

Chris Sidi writes: "instead of having an "inspace" boolean, you can keep track of the previous character and see if both the current character and previous character are spaces:"
Chris Sidi 写道:“我们可以不用‘inspace’这样一个布尔型旗帜变量,通过跟踪判断上一个接收字符是否为空格来进行过滤。”

 
bubuko.com,布布扣
#include <stdio.h>
 
/* count lines in input */
int
main()
{
        int c, pc; /* c = character, pc = previous character */
 
        /* set pc to a value that wouldn‘t match any character, in case
        this program is ever modified to get rid of multiples of other
        characters */
 
        pc = EOF;
 
        while ((c = getchar()) != EOF) {
                if (c ==  )
                        if (pc !=  )   /* or if (pc != c) */ 
                                putchar(c);
 
                /* We haven‘t met ‘else‘ yet, so we have to be a little clumsy */
                if (c !=  )
                        putchar(c);
                pc = c;
        }
 
        return 0;
}
bubuko.com,布布扣


3.利用循环进行过滤

Stig writes: "I am hiding behind the fact that break is mentioned in the introduction"!

 
bubuko.com,布布扣
#include <stdio.h>
 
int main(void)
{
        int c;
        while ((c = getchar()) != EOF) {
                if (c ==  ) {
                       putchar(c);
                       while((c = getchar()) ==   && c != EOF)
                               ;
               }
               if (c == EOF)
                       break; /* the break keyword is mentioned
                               * in the introduction... 
                               * */
 
               putchar(c);
        }
        return 0;
} 
bubuko.com,布布扣

 

c程序设计语言_习题1-9_将输入流复制到输出流,并将多个空格过滤成一个空格,布布扣,bubuko.com

c程序设计语言_习题1-9_将输入流复制到输出流,并将多个空格过滤成一个空格

原文:http://www.cnblogs.com/haore147/p/3647917.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!