c程序设计语言_习题1-9_将输入流复制到输出流,并将多个空格过滤成一个空格
2023-09-11 14:21:33 时间
Write a program to copy its input to its output, replacing each string of one or more blanks by a single blank.
编写这样一个程序,实现将输入流复制到输出流,但是要将输入流中多个空格过滤成一个空格。
1.旗帜变量方法
#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; }
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 <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; }
3.利用循环进行过滤
Stig writes: "I am hiding behind the fact that break
is mentioned in the introduction"!
#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; }
相关文章
- Linux - 标准输入标准输出,重定向
- 输入一个正整数,按照从小到大的顺序输出它的所有质因子(如180的质因子为2 2 3 3 5 )
- 《Visual C++ 开发从入门到精通》——2.4 输入/输出基础
- 《Android应用开发入门经典(第3版)》——第6.2节使用输入控件
- c# 控制台输入和输出
- 【C语言】用递归法将一个整数转换成字符串。例如,输入483,应输出字符串“483”。N的位数不确定,可以是任意的整数(负数/正数)。
- 【C语言】写一函数,求一个字符串的长度。在main函数中输入字符串,并输出其长度。
- 【C语言】写一个函数,输入一个N位数,将这个N位数每两个数字之间插入一个空格并输出。例如输入1234,则输出1 2 3 4
- (第11列)C语言练习:输入数组,最大的与第一个元素交换,最小的与最后一个元素交换,输出数组。五步带你解决。
- 计组 | 【七 输入/输出系统】强化阶段 —— 应用题总结
- 计组 | 【七 输入/输出系统】知识点与例题
- [Spark][Streaming]Spark读取网络输入的例子
- 【校招Verilog进阶挑战】 时序逻辑篇:VL14 自动贩售机1(注意Moore机在输入完成后的时钟周期输出需要使用next_state判断)
- 手把手教你搭建一个深度网络模型:从输入层-激活函数-损失函数-优化方法-输出层-执行训练
- C# 之 文件的输入与输出
- c语言输入与输出库函数#include<stdio.h>
- kali无法执行默认网络浏览器输入/输出错误解决办法