Write a program to remove all trailing blanks and tabs from each line of input, and to delete entirely blank lines.

其实做这道题目有两种思路:

  1.后向模式:利用getline()先将输入流中,每一行完全接收,然后从接收的line字符串中末尾,往前扫,直到发现第一个非空格和制表符字符;

  2.前向模式:每接收一个字符,都要进行输出、判断。

/* K&R2 1-18 p31: Write a program to remove trailing blanks and tabs
from each line of input, and to delete entirely blank lines. The program specification is ambiguous: does "entirely blank lines"
mean lines that contain no characters other than newline, or does
it include lines composed of blanks and tabs followed by newline?
The latter interpretation is taken here. This implementation does not use any features not introduced in the
first chapter of K&R2. As a result, it can't use pointers to
dynamically allocate a buffer to store blanks that it has seen, so
it must limit the number of blanks that are allowed to occur
consecutively. (This is the value of MAXQUEUE, minus one.) It is intended that this implementation "degrades gracefully."
Even though a particular input might have 1000 or more blanks or
tabs in a row, causing a problem for a single pass, multiple passes
through the file will correct the problem. The program signals the
need for such an additional pass by returning a failure code to the
operating system. (EXIT_FAILURE isn't mentioned in the first
chapter of K&R, but I'm making an exception here.) */ #include <stdio.h>
#include <stdlib.h> #define MAXQUEUE 1001 int advance(int pointer)
{
if (pointer < MAXQUEUE - )
return pointer + ;
else
return ;
} int main(void)
{
char blank[MAXQUEUE];
int head, tail;
int nonspace;
int retval;
int c; retval = nonspace = head = tail = ;
while ((c = getchar()) != EOF) {
if (c == '\n') {
head = tail = ;
if (nonspace)
putchar('\n');
nonspace = ;
}
else if (c == ' ' || c == '\t') {

  //能执行这个if,只能说明输入行中字符溢出了。
  if (advance(head) == tail) {
putchar(blank[tail]);
tail = advance(tail);
nonspace = ;
retval = EXIT_FAILURE;
}

    //只要遇到空格和制表符,就先存起来
blank[head] = c;
head = advance(head);
}
else {     //一次性把前面积攒的空格和制表符输出来
while (head != tail) {
putchar(blank[tail]);
tail = advance(tail);
}
putchar(c);
nonspace = ;
}
} return retval;
}

Chris Sidi writes:

Ben,

I thought your solution to 1-18 was really neat (it didn't occur to me
when I was doing the exercise), the way it degrades gracefully and
multiple passes can get rid of huge blocks of whitespace. However, if there is a huge block of non-trailing whitespace (eg "A",2000
spaces, "B\n") your program returns an error when there's not a need for
it. And if someone were to use your program till it passes it will loop
infinitely: $ perl -e 'print "A"," "x2000,"B\n";' > in
$ until ./a.out < in > out; do echo failed, running another pass; cp out
in; done
failed, running another pass
failed, running another pass
failed, running another pass
[snip] Below I have added a variable spaceJustPrinted to your program and check
to see if the spaces printed early are trailing. I hope you like the
minor improvement. (Though I can understand if you don't give a [1] :))

[1] expletive deleted - RJH.

/* K&R2 1-18 p31: Write a program to remove trailing blanks and tabs
from each line of input, and to delete entirely blank lines. The program specification is ambiguous: does "entirely blank lines"
mean lines that contain no characters other than newline, or does
it include lines composed of blanks and tabs followed by newline?
The latter interpretation is taken here. This implementation does not use any features not introduced in the
first chapter of K&R2. As a result, it can't use pointers to
dynamically allocate a buffer to store blanks that it has seen, so
it must limit the number of blanks that are allowed to occur
consecutively. (This is the value of MAXQUEUE, minus one.) It is intended that this implementation "degrades gracefully."
Even though a particular input might have 1000 or more trailing
blanks or tabs in a row, causing a problem for a single pass,
multiple passes through the file will correct the problem. The
program signals the need for such an additional pass by returning a
failure code to the operating system. (EXIT_FAILURE isn't mentioned
in the first chapter of K&R, but I'm making an exception here.) */ #include <stdio.h>
#include <stdlib.h> #define MAXQUEUE 1001 int advance(int pointer)
{
if (pointer < MAXQUEUE - )
return pointer + ;
else
return ;
} int main(void)
{
char blank[MAXQUEUE];
int head, tail;
int nonspace;
int retval;
int c;
int spaceJustPrinted; /*boolean: was the last character printed whitespace?*/ retval = spaceJustPrinted = nonspace = head = tail = ; while ((c = getchar()) != EOF) {
if (c == '\n') {
head = tail = ;
if (spaceJustPrinted == ) /*if some trailing whitespace was printed...*/
retval = EXIT_FAILURE; if (nonspace) {
putchar('\n');
spaceJustPrinted = ; /* this instruction isn't really necessary since
spaceJustPrinted is only used to determine the
return value, but we'll keep this boolean
truthful */
nonspace = ; /* moved inside conditional just to save a needless
assignment */
}
}
else if (c == ' ' || c == '\t') {
if (advance(head) == tail) {
putchar(blank[tail]); /* these whitespace chars being printed early
are only a problem if they are trailing,
which we'll check when we hit a \n or EOF */
spaceJustPrinted = ;
tail = advance(tail);
nonspace = ;
} blank[head] = c;
head = advance(head);
}
else {
while (head != tail) {
putchar(blank[tail]);
tail = advance(tail);
}
putchar(c);
spaceJustPrinted = ;
nonspace = ;
}
} /* if the last line wasn't ended with a newline before the EOF,
we'll need to figure out if trailing space was printed here */
if (spaceJustPrinted == ) /*if some trailing whitespace was printed...*/
retval = EXIT_FAILURE; return retval;
}

c程序设计语言_习题1-18_删除输入流中每一行末尾的空格和制表符,并删除完全是空格的行的更多相关文章

  1. c程序设计语言_习题1-16_自己编写getline()函数,接收整行字符串,并完整输出

    Revise the main routine of the longest-line program so it will correctly print the length of arbitra ...

  2. c程序设计语言_习题7-6_对比两个输入文本文件_输出它们不同的第一行_并且要记录行号

    Write a program to compare two files, printing the first line where they differ. Here's Rick's solut ...

  3. c程序设计语言_习题8-4_重新实现c语言的库函数fseek(FILE*fp,longoffset,intorigin)

      fseek库函数 #include <stdio.h> int fseek(FILE *stream, long int offset, int origin); 返回:成功为0,出错 ...

  4. c程序设计语言_习题8-6_利用malloc()函数,重新实现c语言的库函数calloc()

    The standard library function calloc(n,size) returns a pointer to n objects of size size , with the ...

  5. c程序设计语言_习题1-19_编写函数reverse(s)将字符串s中字符顺序颠倒过来。

    Write a function reverse(s) that reverses the character string s . Use it to write a program that re ...

  6. c程序设计语言_习题1-13_统计输入中单词的长度,并且根据不同长度出现的次数绘制相应的直方图

    Write a program to print a histogram of the lengths of words in its input. It is easy to draw the hi ...

  7. c程序设计语言_习题1-11_学习单元测试,自己生成测试输入文件

    How would you test the word count program? What kinds of input are most likely to uncover bugs if th ...

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

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

  9. 如何删除datatable中的一行数据

    在C#中,如果要删除DataTable中的某一行,大约有以下几种办法: 1,使用DataTable.Rows.Remove(DataRow),或者DataTable.Rows.RemoveAt(ind ...

随机推荐

  1. From MSI to WiX, Part 1 - Required properties, by Alex Shevchuk

    Following content is directly reprinted from From MSI to WiX, Part 1 - Required properties Author: A ...

  2. HttpWatch网络抓包工具的使用

    HttpWatch网络抓包工具是专为IE浏览器集成的一款网络拽包工具.   是一款强大的网页数据分析软件,是最好用的抓包工具,httpwatch可以抓到上传视屏图片的包,一般的抓包软件是抓不到的.打开 ...

  3. spl_autoload_register array参数

    spl_autoload_register (PHP 5 >= 5.1.2) spl_autoload_register — 注册给定的函数作为 __autoload 的实现 说明¶ bool  ...

  4. Linux CPU亲缘性详解

    前言 在淘宝开源自己基于nginx打造的tegine服务器的时候,有这么一项特性引起了笔者的兴趣.“自动根据CPU数目设置进程个数和绑定CPU亲缘性”.当时笔者对CPU亲缘性没有任何概念,当时作者只是 ...

  5. Javascript代码摘录

    判断浏览器窗口高度 if (document.documentElement.clientHeight <800) { var elm = document.getElementById('Di ...

  6. ZeroMQ/jzmq安装使用

    环境: No LSB modules are available. Distributor ID: Ubuntu Description: Ubuntu 12.04.2 LTS Release: 12 ...

  7. 工作流(Workflow)学习---基础知识整理

    工作流定义: 工作流是将一组任务组织起来以完成某个经营过程:定义了任务的触发顺序和触发条件,每个任务可以由一个或多个软件系统完成,也可以由一个或一组人完成,还可以由一个或多个人与软件系统协作完成. 工 ...

  8. 【原创】一起学C++ 之enum ---------C++ primer plus(第6版)

    枚举 定义:在默认情况下讲整数值赋给枚举量,第一个枚举量的值为0,第二个枚举量的值为1,依次+1 一.定义一个枚举,枚举类型,枚举量 *与C#相比个人认为C++的enum不好一点是不能通过枚举名点其中 ...

  9. log4j记录运行日志

    1.在工程中导入log4j-1.2.15.jar的jar包2.新建测试类 package control; import org.apache.log4j.Logger; import org.apa ...

  10. Linux安装包

    关于SWT SWT首先要在Eclipse中添加SWT的安装包:Windowsbuilder Pro.下载路径:http://www.eclipse.org/windowbuilder/download ...