Skip to content
Advertisement

C: finding longest line

I am trying to run this example from (dennis ritchie book), however it does not find the longest line, any idea?

main.c

#include <stdio.h>
#include <stdlib.h>

#include "other.h"



    int main()
    {
        /*printf("Hello world!n");
        printf("%dn",getmynumber());


        start of a new program%= */

        int len;
        int max;
        char line[MAXLINE];
        char longest[MAXLINE];

        max = 0;
        while ((len = getLine(line, MAXLINE)) > 0 )
            if (len > max){
                max = len;
                copyL(longest,line);
            }
        if (max > 0)
            printf("%s", longest);

        return 0;
    }

other.c

#include <stdio.h>
#include "other.h"

int getmynumber(void){
    return 7;
}


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] = '';
    return i;

}


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

other.h

#ifndef OTHER_H_INCLUDED
#define OTHER_H_INCLUDED
#define MAXLINE 1000


int getmynumber(void);
int getLine(char line[], int maxline);
void copyL(char to[], char from[]);


#endif // OTHER_H_INCLUDED

Using debugger: looks like i in copyL function does not increment… any ideas why?

code blocks debug

FIX:

while ((to[i] = from[i]) != ''){
    ++i;
}

Advertisement

Answer

I think you incorrectly transcribed the code. This line:

while ((to[i], from[i]) != '')

is probably incorrect. The expression (to[i], from[i]) is an instance of the comma operator which produces its right hand side as the resulting value. I believe it should instead have been an assignment.

User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement