Hi there. I've been programming in C for a few months, and I've hit a snag with EOF and fgetc. I read Hammer's FAQ article about why it's bad to use feof() in a while loop. I tried it, and like he said the last line of output was repeated. Now that I've adjusted my while loop to use a value determined by fgetc, I'm still having the same problem.
My program is meant to print off the first word of each line of a given .txt document. I program in Ubuntu, and I'm using a the redirection operator "<" to redirect my text file into the stdin stream of my program.
My code is short:
My text file is simply:Code:int main (int argc, char * argv[] ){ char temp[20]; char holder, holder2; fscanf(stdin, "%s", temp); printf("%s\n", temp); holder = fgetc(stdin); while(holder != EOF){ if(holder == '\n') { fscanf(stdin, "%s", temp); printf("%s\n", temp); } holder = fgetc(stdin); } return 1; }
Here is some text
arranged in a strange way
on
each line
END.
The output I receive is:
Here
arranged
on
each
END.
END.
I understand this may be trivial to many of you. I'm not so much looking for code, but more so a clarification of how the EOF is handled; I'd like to figure out which subtlety has been driving me bonkers for the last two hours.