wow..thanks...so now I am able to get the correct length of the longest line, but it does not copy the correct longest line. it simply gives me back the first longest line that passes MAXLINE. However It does give me back the correct one when all the given lines have a length less than MAXLINE. I think something may be wrong with the way im copying it.
Edit: So I fixed it..however I don't see why the copy inside the while loop does not interfere with the one outside of it. I would see why it wouldnt if all the lines were within MAXLINE because it would never reach the point where it adds to possiblemax. However when there are a mixture of lines, the code seems to run fine. I would think the copy outside the while loop would interfere with the one inside. Can someone explain this to me please?
Code:
#include <stdio.h>
#define MAXLINE 10
int getline(char line[], int maxline);
void copy(char to[], char from[]);
//prints longest input line
main(){
int len; //current line length
int max; //maximum length seen so far
int possiblemax; //possible maximum length
int realmax; //the real maximum length
int c; //the char
char line[MAXLINE]; //current input line
char longest[MAXLINE]; //longest line saved here
max = possiblemax = realmax = 0;
while ((len = getline(line, MAXLINE)) > 0){
//checks to see if array ends with a new line
if (line[len - 1] != '\n'){
//while c is not equal to a new line
while ((c = getchar()) != '\n'){
//while c is not a new line add one to possible max
++possiblemax;
}
//if is equal to a new line
if (c == '\n'){
//if possiblemax is greater than real max
//set realmax to possiblemax
//reset possible max
if (possiblemax > realmax){
copy(longest, line);
realmax = possiblemax;
possiblemax = 0;
}
//otherwise reset possiblemax
else possiblemax = 0;
}
}
if (len > max){
max = len;
copy(longest, line);
}
}
realmax = realmax + max;
if (max > 0){ //there was a line
printf("length:%d", realmax);
putchar('\n');
printf("%s", longest);
}
return 0;
}
//read a line into s, return length
int getline(char s[], int lim){
int c, i;
for(i = 0; i < lim-1 && (c = getchar()) != EOF && c != '\n'; ++i)
s[i] = c;
if(c == '\n'){
s[i] = c;
++i;
}
s[i] = '\0';
return i;
}
//copy from into to: assume to is big enough
void copy(char to[], char from[]){
int i;
i = 0;
while ((to[i] = from[i]) != '\0')
++i;
}