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. [技术翻译] 构建现代化的Objective-C (下)

    我的技术博客经常被流氓网站恶意爬取转载.请移步原文:http://www.cnblogs.com/hamhog/p/3563880.html,享受整齐的排版.有效的链接.正确的代码缩进.更好的阅读体验 ...

  2. hdu 1316 How many Fibs?(高精度斐波那契数)

    //  大数继续 Problem Description Recall the definition of the Fibonacci numbers:  f1 := 1  f2 := 2  fn : ...

  3. 【转】SQL删除重复数据方法

    例如: id           name         value 1               a                 pp 2               a           ...

  4. CSS弹性盒模型 box-flex

    目前没有浏览器支持boc-flex属性. Firefox支持代替的-moz-box-flex属性 Safari.Opera以及Chrome支持替代的-webkit-box-flex属性 box-fle ...

  5. 51nod1089最长回文子串V2

    1089 最长回文子串 V2(Manacher算法) 基准时间限制:1 秒 空间限制:131072 KB 分值: 0 难度:基础题 回文串是指aba.abba.cccbccc.aaaa这种左右对称的字 ...

  6. Python 中模块间全局变量的使用上的注意

    最近用Python写代码,需要用到模块间的全局变量. 网上四处搜索,发现普遍做法是把全局变量放到一个独立的模块中,使用时,导入此全局变量模块即可. 但是在实际使用过程中发现了些小问题:在使用如下代码导 ...

  7. eclipse中使用jython

    通过maven配置加载这个包,目前比较稳定的是python2.7的,见 <dependency> <groupId>org.python</groupId> < ...

  8. MVC-列表页操作按钮调用脚本

    如上图所示功能:点击右边的“编辑”和“重置按钮”,调用js实现弹出框功能. 1.写脚本: <script type="text/javascript"> functio ...

  9. CODEVS 3657 括号序列

    [问题描述] 我们用以下规则定义一个合法的括号序列: (1)空序列是合法的 (2)假如S是一个合法的序列,则 (S) 和[S]都是合法的 (3)假如A 和 B 都是合法的,那么AB和BA也是合法的 例 ...

  10. C# and JSON

    JQuery Parse JSON var obj = $.parseJSON(data); C# creates JSON string: public static class JSONHelpe ...