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