C程序设计语言 第1章(2)
练习1-10 编写一个将输入复制到输出的程序,并将其中的制表符替换为\t,把回退符替换为\b,把反斜杠替换为\\,这样可以将制表符和回退符以可见的方式显示出来。
1 #include <stdio.h> 2 int main() 3 { 4 int c; 5 while ((c = getchar()) != EOF) 6 { 7 if (c == '\t') 8 { 9 putchar('\\'); 10 putchar('t'); 11 } 12 else if (c == '\b') 13 { 14 putchar('\\'); 15 putchar('b'); 16 } 17 else if (c == '\\') 18 { 19 putchar('\\'); 20 putchar('\\'); 21 } 22 else 23 { 24 putchar(c); 25 } 26 } 27 return 0; 28 }
练习1-12 编写一个程序,以每行一个单词的形式打印其输入。
1 #include <stdio.h> 2 #define IN 1 3 #define OUT 0 4 int main() 5 { 6 int c; 7 int state = OUT; 8 while ((c = getchar()) != EOF) 9 { 10 if (c == '\n' || c == '\t' || c == ' ') 11 { 12 if (state == IN) 13 putchar('\n'); 14 state = OUT; 15 } 16 else if (state == OUT) 17 { 18 state = IN; 19 } 20 21 if (state == IN) 22 { 23 putchar(c); 24 } 25 } 26 return 0; 27 }
练习1-13 编写一个程序,打印输入中单词长度的直方图。水平方向的直方图比较容易绘制,垂直方向的直方图则要困难些。
1 #include <stdio.h> 2 #define MAXWORD 20 3 #define IN 1 4 #define OUT 0 5 int main() 6 { 7 int c, wordHist[MAXWORD]; 8 int i, j, nw, maxnum; 9 int state; 10 for (i = 0; i < MAXWORD; i++) 11 wordHist[i] = 0; 12 13 state = OUT; 14 nw = 0; 15 while ((c = getchar()) != EOF) 16 { 17 if (c == ' ' || c == '\t' || c == '\n') 18 { 19 if (state == IN) 20 { 21 wordHist[nw]++; 22 nw = 0; 23 } 24 state = OUT; 25 } 26 else 27 { 28 state = IN; 29 } 30 if (state == IN) 31 nw++; 32 } 33 maxnum = wordHist[1]; 34 for (i = 2; i < MAXWORD; i++) 35 { 36 if (maxnum < wordHist[i]) 37 maxnum = wordHist[i]; 38 } 39 40 for (i = 0; i < maxnum; i++) 41 { 42 printf("%d ", maxnum-i); 43 for (j = 1; j < MAXWORD; j++) 44 { 45 if (wordHist[j] >= maxnum-i) 46 printf("- "); 47 else 48 printf(" "); 49 } 50 printf("\n"); 51 } 52 printf("+ "); 53 for (j = 1; j < MAXWORD; j++) 54 printf("%d ", j); 55 printf("\n");
练习1-14 编写一个程序,打印输入中各个字符出现频度的直方图。
练习1-15 重新编写1.2节的温度转换程序,使用函数实现温度转化计算。
练习1-16 对用于打印最长行的程序的主程序 main进行修改,使之可以打印任意长度的输入
行的长度以及文本行中尽可能多的字符。
练习1-18 编写一个程序,删除每个输入行末尾的空格及制表符,并删除完全是空格的行。
1 #include <stdio.h> 2 #define MAXLINE 1000 3 4 int getline(char line[], int maxline); 5 int removes(char s[]); 6 void main () 7 { 8 char line[MAXLINE]; 9 while (getline(line, MAXLINE) > 0) 10 if (removes > 0) 11 { 12 printf("%s", line); 13 } 14 } 15 16 17 int getline(char s[], int lim) 18 { 19 int c, i, j; 20 j = 0; 21 for (i = 0; (c = getchar()) != EOF && c != '\n'; i++) 22 { 23 s[i] = c; 24 ++j; 25 } 26 if (c == '\n') 27 { 28 s[j] = c; 29 ++j; 30 ++i; 31 } 32 s[j] = '\0'; 33 return i; 34 } 35 36 int removes(char s[]) 37 { 38 int i = 0; 39 while (s[i] != '\n') 40 ++i; 41 --i; 42 while (i >= 0 && (s[i] == ' ' || s[i] == '\t')) 43 --i; 44 if (i >= 0) 45 { 46 ++i; 47 s[i] = '\n'; 48 ++i; 49 s[i] = '\0'; 50 } 51 return i; 52 }
很难实现的,才叫梦想!