Question

I am working through K&R and I've attempted to write a program that prints out all input lines greater than 80 characters. Once I run the program on itself from the terminal I get nothing back. Can anyone tell me where I have gone wrong? Also one part which I am unsure of is the line s[i] = '\0'; - can someone please explain to me what this does?

#include <stdio.h>
#define MAXLINE 1000
#define LENGTH 80

int get_line(char line[], int maxline);

/* program to print all lines longer than 80 characters */
main()
{
    int len;    /*current line length*/
    char line[MAXLINE]; /*current input line*/

    while((len = get_line(line, MAXLINE)) > 0)  /*while length of the line is greater than zero*/
            if (len > LENGTH) { /*if the length is greater than 80*/
                    printf("%s", line); /*print that line*/
                    return 0;               
            }
}

/* getline: read a line into s, return length */
int get_line(char s[], int lim)
{
    int c, i;

        for (i=0; i<lim-1 && (c=getchar())!=EOF && c!='\n'; ++i) /*if i is < 1000 & input is = EOF & input is != newline add one*/
            s[i] = c;   /*assign a value to each character*/
    if (c == '\n') {                            
            s[i] = c;
            ++i;
    }
    s[i] = '\0';    /*unsure what '\0' does*/               
    return i;   /*return the length*/
}
Was it helpful?

Solution

The line

s[i] = '\0';

appends a nul terminator to the string. That's C-ism that indicates the end of the string.

As for your issue, this program works just fine for me.

$ cat line80.c | ./line80
  while((len = get_line(line, MAXLINE)) > 0)              /*while length of the line is greater than zero*/

$ ./line80 < line80.c
  while((len = get_line(line, MAXLINE)) > 0)              /*while length of the line is greater than zero*/

OTHER TIPS

The only issue I see with your code is that it stops immediately after printing the first line it finds more than 80 characters long.

If you move the

return 0;

outside the if statement, it will print all lines more than 80 characters instead of just the first.

Your "main" method would then be

main()
{
    int len;                                /*current line length*/
    char line[MAXLINE];                         /*current input line*/

    while((len = get_line(line, MAXLINE)) > 0)              /*while length of the line is greater than zero*/
            if (len > LENGTH)                    /*if the length is greater than 80*/
                    printf("%s", line);                 /*print that line*/

    return 0;
}

As others have noted the '\0' character is a C string termination.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top