I am trying to read from a file that contains zeros or ones in rows like this:
0000100000
0000100000
0000100000
0000100000
I want to store every single number in a 2d array of ints. The issue is that when I try to save a 0 or 1 in the 2d array, I keep getting 48 or 49 instead. My code looks like this:
while (fgets(buffer, INT_MAX, pF) != NULL)
{
for (int x = 0; x < gridW; x++)
{
grid[x][y] = buffer[x];
}
y++;
}
Thanks in advance.
fgets
reads a line of text, so each byte contains the character code for the character that was read.
You can get the number the character represents by subtracting the code for the character '0'
from each character. That will give you values from 0 to 9.
grid[x][y] = buffer[x] - '0';
This assumes of course that the string you read in contains only decimal digits. You'll need to add extra validation if that's not the case.