fscanf EOF problem

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
Check if the return value of fscanf is EOF instead.
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
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
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.