博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
c程序设计语言_习题1-9_将输入流复制到输出流,并将多个空格过滤成一个空格...
阅读量:4563 次
发布时间:2019-06-08

本文共 2149 字,大约阅读时间需要 7 分钟。

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

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

1.旗帜变量方法
#include 
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;}
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’这样一个布尔型旗帜变量,通过跟踪判断上一个接收字符是否为空格来进行过滤。”

 
#include 
/* count lines in input */intmain(){ 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;}
3.利用循环进行过滤

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

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

 

转载于:https://www.cnblogs.com/haore147/p/3647917.html

你可能感兴趣的文章
巧用网盘托管私人Git项目
查看>>
python全栈脱产第19天------常用模块---shelve模块、xml模块、configparser模块、hashlib模块...
查看>>
[LeetCode] House Robber
查看>>
virtualbox中kali虚拟机安装增强功能
查看>>
java生成六位验证码
查看>>
iOS的MVP设计模式
查看>>
stringstream
查看>>
【转】HDU 6194 string string string (2017沈阳网赛-后缀数组)
查看>>
前后端分离
查看>>
存储过程
查看>>
福特F-550 4x4 越野房车设计方案欣赏_房车欣赏_21世纪房车网
查看>>
建立个长春互联网群
查看>>
生成器
查看>>
将一个数的每一位都取出来的方法!
查看>>
2) 十分钟学会android--建立第一个APP,执行Android程序
查看>>
面试题8:二叉树下的一个节点
查看>>
hash冲突的解决方法
查看>>
linux进程 生产者消费者
查看>>
Asp.Net webconfig中使用configSections的用法
查看>>
mysql 二进制日志
查看>>