//统计行数、单词数、字符数#include<stdio.h>#define IN 1#define OUT 0intmain(){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;}elseif(state == OUT){
state = IN;++nw;}}printf("%d %d %d",nl+1,nw,nc);}
练习1-12:以每行一个单词的形式打印
代码:
//以每行一个单词的形式打印其输入#include<stdio.h>#define IN 1#define OUT 0intmain(){int c;while((c =getchar())!=EOF){if(c ==' '|| c =='\n'|| c =='\t'){putchar('\n');}else{putchar(c);}}}
1.6:统计各个数字、空白符、其他符号出现的次数
代码:
//统计各个数字、空白符、其他符号出现的次数#include<stdio.h>intmain(){int c , nwhite , nother;int ndigit[10];
nwhite = nother =0;for(int i =0; i<10; i++){
ndigit[i]=0;}while((c =getchar())!=EOF){if(c >='0'&& c <='9'){++ndigit[c-'0'];}elseif(c ==' '|| c =='\n'|| c =='\t'){++nwhite;}else{++nother;}}printf("\ndigits=");for(int i =0; i<10; i++){printf(" %d",ndigit[i]);}printf(",white space = %d, other space = %d\n",nwhite,nother);}
1.7:power()幂函数的实现
代码:
//power()幂函数的实现#include<stdio.h>intpower(int m,int n);intmain(){for(int i=0; i<10; i++){printf("%d %d %d\n", i,power(2,i),power(-3,i));}return0;}intpower(int base,int n){int p =1;for(int i=1; i<=n; i++){
p = p * base;}return p;}
1.9 :输出长度最长的文本行
代码:
//输出长度最长的文本行#include<stdio.h>#define MAXLINE 1000int_getline(char s[],int lim);voidcopy(char to[],char from[]);intmain(){int len;int max;char line[MAXLINE];char longest[MAXLINE];
max =0;while((len =_getline(line,MAXLINE))>0){if(len > max){
max = len;copy(longest,line);}}if(max >0){printf("%s",longest);}return0;}int_getline(char s[],int lim){int c , i;for(i =0; i<lim-1&&(c =getchar())!=EOF&& c !='\n';++i){
s[i]= c;}if(c =='\n'){
s[i]= c;++i;}
s[i]='\0';return i;}voidcopy(char to[],char from[]){int i =0;while((to[i]= from[i])!='\0'){++i;}}
练习1-16:打印任意长度的输入行的长度,并且尽可能多地打印文本
代码:
//使之可以打印任意长度的输入行的长度,并尽可能地打印文本#include<stdio.h>#define MAXLINE 1000int_getline(char s[],int lim);voidcopy(char to[],char from[]);intmain(){int len;int max;char line[MAXLINE];char longest[MAXLINE];
max =0;while((len =_getline(line,MAXLINE))>0){if(len > max){
max = len;copy(longest,line);}}if(max >0){printf("%s",longest);}return0;}int_getline(char s[],int lim){int c , i;for(i =0; i<lim-1&&(c =getchar())!=EOF&& c !='\n';++i){
s[i]= c;}if(c =='\n'){
s[i]= c;++i;}
s[i]='\0';return i;}voidcopy(char to[],char from[]){int i =0;while((to[i]= from[i])!='\0'){++i;}}