Printf problem with Kernighan and Ritchie problem 1-17
In the code below (for problem 1-17 in "The C Programming Language", by Kernighan and Ritchie) why doesn't it print the longest line (at the bottom)?
#include <stdio.h>
#define MAXLINE 1000
#define LONGLINE 10
int getLineLength(char line[], int maxline){
int i, c;
for(i = 0; i< maxline-1 && (c = getchar() != EOF) && c != '\n'; i++)
line[i] = c;开发者_如何学Go
if(c == '\n') {
line[i] = c;
i++;
}
line[i] = '\0';
return i;
}
main() {
int len;
char line[MAXLINE];
while((len = getLineLength(line, MAXLINE)) > 0)
if(len > LONGLINE)
printf("The line was over the maxlength\n\t %s", line);
return 0;
}
In your code:
(c = getchar() != EOF)
This will be evaluated as (c = (getchar() != EOF))
, giving the wrong result. What you need is:
((c = getchar()) != EOF)
This program reads from standard input, and prints that long message for lines longer 10 than characters. Lines end with '\n' (newline, ENTER). Input ends with EOF, if you feed a file, e.g. through a pipe, or CTRL-C, if you enter characters manually.
I'm surprised this works at all. (c = getchar() != EOF)
is completely wrong for a start. line[i] = c;
appears twice. And I think it's vulnerable to a buffer overflow in an edge case.
EDIT: An earlier answer that I can't see any more said that you seem to have your braces missing from the for loop.
精彩评论