Chinaunix

标题: K&R中的一道练习题 [打印本页]

作者: meiyuhan    时间: 2007-04-26 17:22
标题: K&R中的一道练习题
练习1-16  修改打印最长文本行的程序的主程序main,使之可以打印任意长度的输入行的长度,并尽可能多地打印文本。




对函数/* getline: read a line into s, return length */
int getline(char s[], int lim)
{
  int c, i, j;
  j=0;
  for(i = 0; (c = getchar())!=EOF && c != '\n'; ++i)
  
    if(i < lim - 2){
      s[j] = c;
      ++j;
    }
  
  if(c == '\n')
    {
      s[j] = c;
      ++j;
      ++i;
      }
  s[j] = '\0';
  return i;
}

不明白啊,GGJJ们帮忙分析一下。谢了。

答案可参考:http://users.powernet.co.uk/eton/kandr2/krx116.html

[ 本帖最后由 meiyuhan 于 2007-4-26 17:36 编辑 ]
作者: meiyuhan    时间: 2007-04-26 17:39
晕,盯着看了半天,看懂了

/* 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;
    }
  }
  if(c == '\n')
  {
    if(i <= lim - 1)
    {
      s[j++] = c;
    }
    ++i;
  }
  s[j] = '\0';
  return i;
}
这样写更容易理解.

[ 本帖最后由 meiyuhan 于 2007-4-26 17:44 编辑 ]
作者: MMMIX    时间: 2007-04-26 18:16
原帖由 meiyuhan 于 2007-4-26 17:39 发表
晕,盯着看了半天,看懂了

这不挺好嘛,非要到论坛上发贴问。
作者: langue    时间: 2007-04-26 18:50
原帖由 MMMIX 于 2007-4-26 18:16 发表

这不挺好嘛,非要到论坛上发贴问。


我倒是想,如果楼主能再多加上点心得体会,多些内容,这个帖就能成为原创精华了。

.
作者: btclx    时间: 2007-04-27 14:11
到论坛发贴..


好啊

呵呵
可以让我也看懂  嘻嘻
作者: imonyse    时间: 2007-04-27 14:57
Chris writes: "Looks like Mr. Kernighan meant for "main routine" in Exercise 1-16 to refer to function main(), saying your solution of modifying getline() is "too easy."

comp.lang.c应该是这方面最大的新闻组资源了吧
i think "Revising the main routine" means, just modifying the "main" function and that is what i did. i did not change anything in "getline" or "copy" functions.

solution by arnuld(mailto:geek.arnuld@gmail.com)

  1. /* K&R2: 1.9, Character Arrays, exercise 1.16

  2. STATEMENT:
  3. revise the main routine of the longest-line programme
  4. so it will correctly print the length of the arbitrarily
  5. long input lines including as much of th possible text.
  6. */

  7. #include<stdio.h>

  8. #define MAXLINE 1000

  9. int getline(char [], int max);
  10. void copy(char from[], char to[]);

  11. int main()
  12. {
  13.   int len = 0; /* current line length */
  14.   char line[MAXLINE]; /* current input line */

  15.   while((len = getline(line, MAXLINE)) > 0)
  16.     {
  17.       printf("LENGTH: %d\n", len);
  18.       printf("LINE-CONTENTS:  %s\n", line);
  19.     }

  20.   return 0;
  21. }


  22. int getline(char line[], int max)
  23. {
  24.   int i = 0; /* simply an index counter */
  25.   int c = 0; /* variale to store user input */

  26.   for(i = 0; ((c = getchar()) != EOF) && c != '\n' && i < max - 1; ++i)
  27.     line[i] = c;

  28.   if(c == '\n')
  29.     line[i++] = c;

  30.   line[i] = '\0';

  31.   return i;
  32. }

复制代码

[ 本帖最后由 imonyse 于 2007-4-30 12:54 编辑 ]




欢迎光临 Chinaunix (http://bbs.chinaunix.net/) Powered by Discuz! X3.2