c - print longest input line.(example in K&R(2e)(section 1.9)) -
when executing program (in ubuntu) , enter input ($ represents eof(ctrl+d)) :-
giujb bjb $$
it not work
input
giujb bjb $$$
it works.
i think should require give eof twice (in program). can explain why requires give eof 3 times?
my code
#include<stdio.h> #define maxlength 1000 char line[maxlength]; char longest[maxlength]; int getlength(); void copy(); int main() { int max=0,leng=0; while((leng=getlength())>0) { if(leng>max) {max=leng; copy(); } } if(max>0) printf("\n%s",longest); return 0; } int getlength() { char ch; int i; for(i=0;(i<(maxlength-1)) && ((ch=getchar())!= eof) && (ch!='\n');++i) {line[i]=ch; printf("%d",i); } if(ch=='\n') {line[i]=ch; ++i; } line[i]='\0'; printf("bye"); return i; } void copy() { int i=0; while((longest[i]=line[i])!='\0') ++i; }
on linux, ctrl-d not mean end-of-file (eof). means 'end-of-transmission', means typed input sent program. similar newline exception ctrl-d not sent. getchar
returns eof when receives empty "transmission". why have type ctrl-d 3 times (or newline followed 2 ctrl-d) 2 eofs.
Comments
Post a Comment