练习1-16:修改打印最长文本行的程序的主程序main,使之可以打印任意长度的输入行的长度,并尽可能多地打印文本(C程序设计语言 第2版)
2013-09-18 18:51
701 查看
该书英文配套答案
View Code
Answer to Exercise 1-16, page 30 Revise the main routine of the longest-line program so it will correctly print the length of arbitrarily long input lines, and as much as possible of the text. /* This is the first program exercise where the spec isn't entirely * clear. The spec says, 'Revise the main routine', but the true * length of an input line can only be determined by modifying * getline. So that's what we'll do. getline will now return the * actual length of the line rather than the number of characters * read into the array passed to it. */ #include <stdio.h> #define MAXLINE 1000 /* maximum input line size */ int getline(char line[], int maxline); void copy(char to[], char from[]); /* print longest input line */ int main(void) { int len; /* current line length */ int max; /* maximum length seen so far */ char line[MAXLINE]; /* current input line */ char longest[MAXLINE]; /* longest line saved here */ max = 0; while((len = getline(line, MAXLINE)) > 0) { printf("%d: %s", len, line); if(len > max) { max = len; copy(longest, line); } } if(max > 0) { printf("Longest is %d characters:\n%s", max, longest); } printf("\n"); return 0; } /* getline: read a line into s, return length */ int getline(char s[], int lim) { int c, i, j; for(i = 0, j = 0; (c = getchar())!=EOF && c != '\n'; ++i) { if(i < lim - 1) { s[j++] = c; } }//这里getline修改后,i可以大于lim限制,只计数,不保存字符。 if(c == '\n') { if(i <= lim - 1) { s[j++] = c; } ++i; } s[j] = '\0'; return i; } /* copy: copy 'from' into 'to'; assume 'to' is big enough */ void copy(char to[], char from[]) { int i; i = 0; while((to[i] = from[i]) != '\0') { ++i; } }
View Code
相关文章推荐
- C程序设计语言练习1-16 修改打印最长文本行的程序的主程序main,使之可以打印任意长度的输入行的长度,并尽可能多的打印文本
- 练习1-16 修改打印最长文本行的程序的主程序main,使之可以打印任意长度的输入行的长度,并尽可能多地打印文本。
- 练习1-16 修改打印最长文本行的程序的主程序main, 使之可以打印任意长度的输入行的长度, 并尽可能多的打印文本。
- 1.16 修改打印最长文本行的程序的主程序main,使之可以打印任意长度的输入行的长度,并尽可能多地打印文本。
- 练习1-13:编写一个程序,打印输入中单词长度的直方图(水平)(C程序设计语言 第2版)
- 练习1-12:编写一个程序,以每行一个单词的形式打印其输入(C程序设计语言 第2版)
- C语言程序设计习题1-16 打印任意长度的输入行的长度,并尽可能多地打印文本
- 编写一个程序,一行行地读取输入行,直至到达文件尾。算出每行输入行的长度,然后把最长的那行打印出来。为了简单起见,你可以假定所有的输入行均不超过1000个字符。
- 编写一个程序,一行行地读取输入行,直至到达文件尾。算出每行输入行的长度,然后把最长的那行打印出来。为了简单起见,你可以假定所有的输入行均不超过1000个字符
- C程序设计语言,练习1-13,编写一个程序,打印输入单词的直方图(垂直方向)
- 编写一个程序,一行行地读取输入行,直至到达文件尾。算出每行输入行的长度,然后把最长的那行打印出来。为了简单起见,你可以假定所有的输入行均不超过1000个字符
- 编写一个程序,一行行的读取输入行,直至到达文件尾。算出每行输入行的长度,然后把最长的那行打印出来
- go语言之map练习(二):编写一个程序wordfreq程序,统计输入文本中每个单词出现的频率(次数)
- 练习1-13 编写一个程序,打印输入中单词长度的直方图(垂直)
- 练习1-13 编写一个程序,打印输入中单词长度的直方图(水平)(方法2)
- 练习1-21:编写程序entab,将空格串替换为最少数量的制表符和空格。。。(C程序设计语言 第2版)
- 练习1-17 编写一个程序,打印长度大于80个字符的所有输入行.
- 练习1-17 编写一个程序,打印长度大于80个字符的所有输入行。
- 练习 1 - 13 编写一个程序,打印输入中单词长度的水平直方图 和 垂直直方图
- 练习1-13 编写一个程序,打印输入中单词长度的直方图(水平)