搜索此博客

2008年2月5日星期二

C 语言练习一则

K & R C Exercise 1-9:将输入拷贝到输出,并将多于一个连续空格转换为一个空格。


29 #include<stdio.h>
30
31 /* Read input and replace one or more blanks by a single blank */
32 main()
33 {
34 int c, bl;
35
36 bl = 0; /* bl used as a flag to determine whether a blank is needed before putchar( c )*/
37 while ((c = getchar()) != EOF)
38 if ((c != ' ') && (bl == 0))
39 putchar( c );
40 else if ((c != ' ') && (bl != 0))
41 {
42 putchar(' ');
43 putchar( c );
44 bl = 0; /* bl != 0 means blank(s) in front and needs to be dealt with */
45 }
46 else
47 {
48 ++bl;
49 }
50 }

我知道标准答案肯定不是这样的,因为还没有学 else 和 && 呢……

这里给出了一些解法。

没有评论:

发表评论