Even though you did check if the file was opened you still continue reading when it failed, that’s wrong, this code will not fail that way, but I assume it will not work either because your file apparently doesn’t exist
Also, in the printing loop you are trying to print more elements than there are in the array, I’ve also fixed that
#include <stdio.h>
#include <stdlib.h>
void sudoku_checker(int N ,int a[])
{
int i,j;
int count;
/* This loop calculate the sum of each row */
/* and check foreach if it equals to (1+2+3+4+5+6+7+8+9) = 45 o not*/
count = 0;
for (i = 0; i < N * N ; i = i + 9)
{
int sumRow = 0;
for (j = i; j < i + 9; j++)
sumRow = sumRow + a[j];
if (sumRow != 45)
count++;
}
/* This loop calculate the sum of each col*/
/* and check foreach if it equals to (1+2+3+4+5+6+7+8+9) = 45 o not*/
for (i = 0; i < N; i++)
{
int sumCol = 0;
for (j = i ; j < N * N; j = j + 9)
sumCol = sumCol + a[j];
if (sumCol != 45)
count++;
}
printf("Fails: %d\n", count);
if (count == 0)
printf("OK\n");
else
printf("Successes\n");
}
int main()
{
//info.txt it's the sudoku file
int i, j, k, arrayofNumbers[81];
FILE *myFile;
int N = 9;
int readCount = 0;
myFile = fopen("file.dat", "r");
if (myFile == NULL)
{
printf("the file could not be opened for reading\n");
/* you should abort the program, if the file was not found */
return -1;
}
while (fscanf(myFile, "%1d", &arrayofNumbers[i]) == 1)
readCount++;
for (j = 0 ; j < readCount ; ++j)
{
printf(" %1d ", arrayofNumbers[j]);
if ((1 + j) % 4 == 0)
printf("\n");
}
sudoku_checker(N,arrayofNumbers);
return 0;
}
3
solved Create int array from txt file with multilines and spaces between numbers in C [closed]