c - Can't find the bug in the program to print the longest input line -
#include <stdio.h> #include <stdlib.h> #define maxline 1000 int mygetline( char line[], int maxline); /*will return length */ void copy (char to[], char from[]); int main(){ int len; // length of line int max; // maximum length seen far char line[maxline]; char longest[maxline]; max = 0; while((len = mygetline(line, maxline)) >0){ if (len>max){ max = len; copy(longest, line); } if (max>0){ printf("%s", longest); } } return 0; } /*getline: reads line s, , returns length of line */ int mygetline(char s[], int limit){ int c, i; for(i=0; i<limit-1 && (c=getchar())!= eof && c!= '\n'; ++i){ s[i] = c; } if (c=='\n'){ s[i] = c; ++i; } s[i] = '\0'; return i; } /*copy: copy 'from' 'to'; assume big enough */ void copy (char to[], char from[]){ int i=0; while((to[i] = from[i] != '\0')){ ++i; } }
above stated code printing longest input line. code compiling without errors , yet when running program not printing anything. can't find going wrong in here.
this bit simpler , job using available string functions, instead of examining char char. if need to, can open file input , replace stdin
.
#include <stdio.h> #include <string.h> #define maxline 1000 int main(){ int len; // length of line int max; // maximum length seen far char line[maxline]; char longest[maxline]; char *sptr; max = 0; while((sptr = fgets(line, maxline, stdin)) != null) { if ((sptr = strtok(sptr, "\r\n")) != null) { len = strlen(sptr); if (len > max) { max = len; strcpy(longest, sptr); } } } if (max) printf("%d: %s\n", max, longest); else printf("no strings read\n"); return 0; }
Comments
Post a Comment