fgets problem

This is strictly C, and not c++, but I hope I wont get a raging mob after me for it:p

Im trying to read a file line by line using fgets. The file im trying to read looks like this:

0000BBBBB0000
00000B0000000
0000000000000
B00000000000B
B00000W00000B
B0000WWW0000B
BB00WWWWW00BB
B0000WWW0000B
B00000W00000B
B00000000000B
0000000000000
000000B000000
000BBBBBBB000

The code that reads the file:

1
2
3
4
5
for (int y = 0; y < kMaxLine; y++) {
		printf("%d", y);
		fgets(l, kMaxLine+1, fp);
		printf("%s", l);
	}


When I run this, I get the following output:


00000BBBBB00001
200000B00000003
400000000000005
6B00000000000B7
8B00000W00000B9
10B0000WWW0000B11
12BB00WWWWW00BB


I'm guessing somehow the '\n' character on each line is getting read twice, or something. Does anyone know what's going on?

Peace
http://www.cplusplus.com/reference/clibrary/cstdio/fgets/
num
Maximum number of characters to be read (including the final null-character).
My guess is that kMaxLine = 13. +1 = 14. you want 13 chars and a '\0'. But fgets will also retrieve the '\n'. So the first fgets reads 13 chars and adds '\0'. the second immediately finds the '\n'.
You could either increase the size of your array, or add a getchar after fgets to deal with '\n'.
Last edited on
Awesome, increasing the array worked perfectly! Thanks;)
Topic archived. No new replies allowed.