这里列举一些代码的习惯比较,想想why可以这样做
1、copy input to output
#include <stdio.h>
/* copy input to output; 1st version */ main() { int c;
c = getchar(); while (c != EOF) { putchar(c); c = getchar(); } }
|
#include <stdio.h>
/* copy input to output; 2nd version */ main() { int c;
while ((c = getchar()) != EOF) putchar(c); }
|
EOF到底是什么,不妨自己动手看下
printf("%d",EOF);//-1
2、characters count
#include <stdio.h>
/* count characters in input; 1st version */ main() { long nc;
nc = 0; while (getchar() != EOF) ++nc; printf("%ld\n", nc); }
|
#include <stdio.h>
/* count characters in input; 2nd version */ main() { double nc;
for (nc = 0; gechar() != EOF; ++nc) ; printf("%.0f\n", nc); }
|
同理:Line Counting
#include <stdio.h>
/* count lines in input */ main() { int c, nl;
nl = 0; while ((c = getchar()) != EOF) if (c == '\n') ++nl; printf("%d\n", nl); }
|
3、Word Counting
#include <stdio.h>
#define IN 1 /* inside a word */ #define OUT 0 /* outside a word */
/* count lines, words, and characters in input */ main() { int c, nl, nw, nc, state;
state = OUT; nl = nw = nc = 0; while ((c = getchar()) != EOF) { ++nc; if (c == '\n') ++nl; if (c == ' ' || c == '\n' || c = '\t') state = OUT; else if (state == OUT) { state = IN; ++nw; } } printf("%d %d %d\n", nl, nw, nc); }
|
待续
阅读(2497) | 评论(0) | 转发(0) |