C 两个习题
2019-03-20 本文已影响0人
吃柠檬的鸮
练习 1 - 8 编写一个统计空格、制表符与换行符个数的程序。
/* ex08.c */
#include <stdio.h>
int main() {
int c;
long spacecnt = 0, tabcnt = 0, nlcnt = 0;
while((c = getchar()) != EOF) {
if ( c == ' ') {
++spacecnt;
} else if (c == '\t') {
++tabcnt;
} else if (c == '\n') {
++nlcnt;
}
}
printf("spacecnt:\t%ld\n", spacecnt);
printf("tabcnt:\t\t%ld\n", tabcnt);
printf("newlinecnt:\t%ld\n", nlcnt);
return 0;
}
编译运行结果如下:
$ ./ex08.out
When you are old and grey and full of sleep,
And nodding by the fire, take down this book,
And slowly read, and dream of the soft look,
spacecnt: 13
tabcnt: 12
newlinecnt: 6
练习 1 - 9 编写一个将输入复制到输出的程序,并将其中连续的多个空格用一个空格代替。
/* ex09.c */
#include <stdio.h>
int main() {
int isspace = 0, c;
while ((c = getchar()) != EOF) {
if (c != ' ') {
isspace = 0;
} else if (!isspace) {
isspace = 1;
} else {
continue;
}
putchar(c);
}
return 0;
}
isspace 可以看成一个标志位,用来标识上一个字符是否是一个空格。
程序中用到了一个 continue
语句,while
循环中 continue
语句的执行意味着立即执行条件测试语句,而忽略当前循环中剩下的内容。
程序编译运行结果如下:
$ ./ex09.out
When you are old and grey and full of sleep,
When you are old and grey and full of sleep,
也可以声明两个变量,一个用来存储上一个字符的值,一个用来存储当前读入的字符,代码清单如下:
/* ex09_2.c */
#include <stdio.h>
int main() {
int cur, pre;
/* 为了便于第一个输入的字符比较,需要给 pre 赋非空格初值 */
pre = EOF;
while ((cur = getchar()) != EOF) {
if (cur == ' ') {
if (pre == ' ') {
continue;
}
}
putchar(cur);
pre = cur;
}
return 0;
}
编译运行结果:
$ ./ex09_2.out
When you are old and grey and full of sleep,
When you are old and grey and full of sleep,