The first column is printed out as (0, 0)
, because atoi
fails. Please don't use atoi
, but rather use strtol
which will make you enable to check if the conversion was successful or not.
The reason why atoi
fails is because you have an extra \n
character, because with fgets(fgets(line, 2, fp);
you're reading only one character - because you passed 2 for size of buffer, and 1 element of the buffer is reserved for the \0
character. Just use enough big buffer to read the entire line, and pass the size of the buffer there.
In order to fix the other error, just don't use feof
. Rather check the fgets
return value to see how many characters it read from the file (or, if you really want to use feof
make that check after the fgets
call).
while ( fgets(line, sizeof(line), fp) > 0)
{
char* end;
alive_row = strtol(&line[0], &end, 10);
// If the end points to the &line[0], then no
// characters were converted!
if(end == &line[0])
{
printf("strtol failed!\n");
return 0;
}
alive_column = strtol(&line[2], &end, 10);
// If the end points to the &line[2], then no
// characters were converted!
if(end == &line[2])
{
printf("strtol failed!\n");
return 0;
}
fprintf(stderr, "\n Cell: (%i)(%i)", alive_row, alive_column);
}
We have a check &line[0] == end
because the second argument passed to strtol
is
Reference to an object of type char*, whose value is set by the function to the next character in str after the numerical value.
If there was no numerical value in the string, this pointer will point to the beginning of the string you've tried to convert.
If you don't know if the number of the digits will be 1 or 2, or any, you still can use strtol
to help you here:
while ( fgets(line, sizeof(line), fp) > 0)
{
char* end;
char* tmp;
alive_row = strtol(&line[0], &end, 10);
// If the end points to the &line[0], then no
// characters were converted!
if(end == &line[0])
{
printf("strtol failed!\n");
return 0;
}
// If the previous strtol converted the first number
// end will point to the space character (the first character after the number).
// So, just pass
// end + 1 which should point to the second number
tmp = end + 1;
alive_column = strtol(tmp, &end, 10);
// If the end points to the tmp, then no
// characters were converted!
// (this is why we used this tmp to place end + 1 - we need to
// check for the success of the strtol).
if(end == tmp)
{
printf("strtol failed!\n");
return 0;
}
fprintf(stderr, "\n Cell: (%i)(%i)", alive_row, alive_column);
}