Search code examples
cwhile-loopmaxc-strings

Length of line in function defaults to 1 after first user input, why?


I am practicing an algorithm from the C programming book and want to output the length of each line after it is typed. After I write a sentence, it gives me the correct out put of "This is a line of length 10" or something. Then in keeps repeating "This is a line of length 1" over and over until I control +z. How can I get it to just print the length and then continue to receive input each time?

#include <stdio.h>
#define MAXLINE 1000 /* maximum input line size */

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

/* print longest input line */

int main()
{
    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 = getlines(line, MAXLINE)) > 0)
        printf("This is the line length %d.", len);
        if (len > max) {
            max = len;
            copy(longest, line);
        }
    if (max > 0) /* there was a line */
        printf("%s", longest);
    return 0;
}

/* getline: read a line into s, return length */
int getlines(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;
}

/* 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++;
}

Thank you.


Solution

  • You forgot to enclose statements of the while loop in braces and you need to change the condition of the loop.

    while ((len = getlines(line, MAXLINE)) > 1 )
    {
        printf("This is the line length %d.", len);
        if (len > max) {
            max = len;
            copy(longest, line);
        }
    }
    

    Or the condition in the while loop can look like

    while ((len = getlines(line, MAXLINE)) != 0 && line[0] != '\n' )
    

    Pay attention to that the second parameter of the function copy should have the qualifier const

    void copy(char to[], const char from[]);