Sunday, May 10, 2009

Problem with a simple C program?

I'm writing a C program that reads the text in a file, and prints it to the screen in a formatted way. This is the code I have written:





#include %26lt;stdio.h%26gt;


#include %26lt;stdlib.h%26gt;





int main()


{


char c;


FILE *book;


book=fopen("Tale.txt", "r");


fscanf(book, "%c", %26amp;c);


printf("%c", c);


while (fscanf(book, "%c", %26amp;c)!=EOF) {


printf("%c", c);


if (c=='.' || c==',' || c=='-') {


printf("\n"); }


}


printf("\n");


fclose(book);


system ("PAUSE");


return 0;


}





It works fine, but I wanted to take the fscanf inside the loop and have something like this:





while (c!=EOF) {


printf("%c", c);


if (c=='.' || c==',' || c=='-') {


printf("\n"); }


fscanf(book, "%c", %26amp;c);


}





But when I do this, the program doesn't stop at the end of the file, and keeps printing dots (the text in the file ends with a dot)





Can somebody tell me what's the problem here?

Problem with a simple C program?
Change to do/while construct since you're no longer checking the status of fscan():





fscanf(book, "%c", %26amp;c);


do {


printf("%c", c);


if (c=='.' || c==',' || c=='-') {


printf("\n"); }


while (fscanf(book, "%c", %26amp;c)!=EOF);


}
Reply:In your first bit of code, the test to see if you are at EOF is made using the return value of fscanf and not the value of the variable c.





fscanf returns the number of input items assigned so you could do something like:





int status = 1;





status = fscanf(...);


while( status )


{


:


:


status = fscanf(...)


}





You could also do:


while( !feof( book ) )


{


}





You will still need to do an initial scanf() before the while starts or you will have garbage as your first character out.
Reply:Your version that works is checking the return of fscanf, which is what you need to do to know when EOF is encountered.





Not sure what your were trying by putting fscanf inside the loop. What you should do is write it so you don't need two calls to fscanf. Something like this, if you want fscanf inside the loop:





int done = 0;


do {


if (fscanf(book,"%c",%26amp;c) != EOF) {


...


}


else done = 1;


} while (!done);





There are many ways you can set up the loop. The point is it's better to not treat the first character in the file as a special case.


No comments:

Post a Comment