fscanf EOF problem

Dec 3, 2011 at 1:06am
I have a simple text file that contains this:
A B
B C
E X
C D
(newline here)

I want to capture the non-whitespace characters from the file and enter them into a char array. I get a segmentation fault with this:
1
2
3
4
5
6
7
		char c;
		fscanf(infile, "%c ", &c);
		for( int i = 0; c != EOF; i++ ) {
			vertArray[i] = c;
			printf("%c ", c);
			fscanf(infile, "%c ", &c);
			} // for 

I know it's an EOF problem because when I change the 'for' condition to something like i < 20, it almost works - except it'll read 'D' forever (i.e. with my printf, all the letters will print, but the last letter, 'D' is printed a bunch of times. How do I fix this? Thanks.


BTW - writing in C not C++ (but this should work for both anyway, right?)
Last edited on Dec 3, 2011 at 1:09am
Dec 3, 2011 at 1:10am
Check if the return value of fscanf is EOF instead.
Dec 3, 2011 at 1:23am
Thanks Peter. It now exits the loop using your suggestion, however the characters it gets are only:
A B E C

I suppose my formatting may be faulty - can you take a look?(on the input file, two spaces between the two letters on each line)
Last edited on Dec 3, 2011 at 1:26am
Dec 3, 2011 at 1:29am
1
2
3
4
5
6
char c;
for (int i = 0; fscanf(infile, "%c ", &c) != EOF; i++)
{
	vertArray[i] = c;
	printf("%c ", c);
}

Last edited on Dec 3, 2011 at 1:33am
Dec 3, 2011 at 1:32am
Aha - I left the original fscanf at the end of the for loop. Works now - here's what it looks like:
1
2
3
4
5
		char c;
		for( int i = 0; fscanf(infile, "%c ", &c) != EOF; i++ ) {
			vertArray[i] = c;
			printf("%c ", c);
			} // for 

Thanks for the assist!
Topic archived. No new replies allowed.