Wednesday, August 17, 2011

Exercise 1-16

Exercise 1-16  Revise the main routine of the longest-line program (below) so it will correctly print the length of arbitrarily long input lines, and as much as possible of the text.


#include <stdio.h>

#define MAXLINE 1000

int getline(char line[], int maxline);
void copy(char to[], char from[]);

int main(void)
{
  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);

  return 0;
}

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;
}

void copy (char to[], char from[])
{
  int i;
  i = 0;
  while ((to[i] = from[i]) !=0)
    ++i;
}


Firstly, I'm not entirely sure what this question is asking for, but here's one idea:

#include <stdio.h>

#define MAXLINE 1000

int getline(char line[], int maxline);
void copy(char to[], char from[]);

int main(void)
{
  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("%d chars: %s", max, longest);

  return 0;
}

int getline(char s[], int lim)
{
  int c, i;

  i = 0;
  while (c=getchar(), c!=EOF && c!='\n')
  {
    if (i<lim-1)
      s[i]=c;
    i++;
  }

  if ((c=='\n') && (i<lim-1))
    s[i++] = '\n';

  if (i<lim)
    s[i] = 0;

  return i;
}

void copy (char to[], char from[])
{
  int i;
  i = 0;
  while ((to[i] = from[i]) !=0)
    ++i;
}



No comments:

Post a Comment