I am starting to learn C and do it with the "c programming language" by
Kerningham and Ritchie. I am currently at page 31.
there is an example program which has to be refined:
Code:
#include <stdio.h>
#define MAXLINE 1000
int getLine(char line[], int maxline);
void copy(char to[], char from[]);
int main(){
int len,max,m;
char line[MAXLINE];
char longest[MAXLINE];
m=0;
max =0;
while((len=getLine(line, MAXLINE)) > 0)
if(len > max) {
max = len;
copy(longest, line);
}
}
if(max > 0)
printf("%s\n", longest);
return 0;
}
in an followup excercise i should handle an error, coming to life, after a
line is fed in longer than MAXSIZE. for this i should display the actual length of the line and display the maximum amount of chars i can (which is MAXSIZE -1).
I use the function getLine, which looks like this:
Code:
int getLine(char s[], int lim){
int c,i;
for(i=0; i<lim-1 && (g=getchar()) != EOF && c != '\n'; ++i)
s[i] = c;
if(c == '\n'){
s[i] = c;
++i;
}
s[i] = '\0';
return i;
}
when i implement my solution inside the while loop where i call the function "getLine"(using the function getchar()) like this:
Code:
while((len=getLine(line, MAXLINE)) > 0)
if(len > max) {
max = len;
copy(longest, line);
if(max == MAXLINE -1 && longest[MAXLINE-1] == '\0'
&& longest[MAXLINE-2] != '\n'){
int c;
while((c=getchar()) != EOF && c != '\n'){
++m;
}
printf("input line too long.\n chars: %d\n", m+MAXLINE);
}
}
..code refer to the main program at the top
}
i get the proper output and count of chars from input.
BUT when i call getchar() outside the while loop. where I call the function using getchar to get the initial input. like this:
Code:
...code refer to the whole program at the top
if(max > 0){
if(max == MAXLINE -1 && longest[MAXLINE-1] == '\0'
&& longest[MAXLINE-2] != '\n'){
int c;
while((c=getchar()) != EOF && c != '\n'){
++m;
}
printf("input line too long.\n chars: %d\n", m+MAXLINE);
}
}
then c == -1 which is equal to EOF.
My Question is the following:
why does it seem that the input buffer is getting emptied as soon as i leave the loop where i first read it with getchar()?
I am a beginner and just starting out with c. as this is a relative hard problem to search for i thought ill ask here. thanks for your time. i am open to any suggestions.
yay first post