Hi everyone,
Once again i call upon your collective or individual expertise!
I'm writing a program (which i have working) and i wanted to put a bit of sanity checking or error checking in to it (using stderr) and its doing something a little funny!
My code:
Code:
#include <stdio.h>
int main()
{
int originalarray[9][9]; // 9x9 matrix, note that the elements are numbered from 0 and that (9,9) isn't used.
int x, y, z; // Coordinate variables
int error;
FILE *array_output;
FILE *formatted_input_file;
// Build original matrix
//***********************************************************************************************************************
if ((formatted_input_file = fopen("formatted_input_file", "r")) == NULL)
fprintf(stderr, "Cannot open %s\n", "formatted_input_file");
for (x = 0; x <= 8; x++)
{
char buf[10];
fscanf(formatted_input_file, "%s", buf);
for (y = 0; y <= 8; y++)
{
originalarray[x][y] = buf[y]-'0';
}
}
fclose(formatted_input_file);
//Print out original array to output file and stdout
//***********************************************************************************************************************
if ((array_output = fopen("array_output", "w")) == NULL)
fprintf(stderr, "Cannot open %s\n", "array_output");
for (x = 0; x < 9; x++) //Goes through rows
{
printf("\n");
fprintf(array_output, "\n");
for (y = 0; y < 9; y++) //Goes through columns
{
printf("%d ", originalarray[x][y]);
fprintf(array_output, "%d ", originalarray[x][y]); // prints each value of the original matrix in turn
}
}
fclose(array_output);
//@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
//Error checking section
error = 0;
for (x = 0; x < 9; x++)
{
for (y = 0; y < 9; y++)
{
for (z = 0; z < 9; z++)
{
if(y != z)
{
if(originalarray[x][y] != 0)
{
if(originalarray[x][y] == originalarray[x][z])
{
error++;
}
}
}
}
}
}
if(error > 0)
{
fprintf(stderr, "\nInput Matrix is Wrong!\n");
}
}
The output is:
Code:
0 2 0 5 0 0 6 4 2
7 0 0 0 0 0 5 0 0
0 3 0 2 0 8 0 0 7
4 0 0 0 0 7 2 9 0
2 8 0 0 0 0 0 6 3
0 7 3 9 0 0 0 0 4
6 0 0 8 0 1 0 7 0
0 0 5 0 0 0 0 0 6
Input Matrix is Wrong!
0 9 7 0 0 2 0 8 0
But it should be (or rather i want it to be):
Code:
0 2 0 5 0 0 6 4 2
7 0 0 0 0 0 5 0 0
0 3 0 2 0 8 0 0 7
4 0 0 0 0 7 2 9 0
2 8 0 0 0 0 0 6 3
0 7 3 9 0 0 0 0 4
6 0 0 8 0 1 0 7 0
0 0 5 0 0 0 0 0 6
0 9 7 0 0 2 0 8 0
Input Matrix is Wrong!
I think i've probably done something really simple but i really can't spot it!
Thanks in advance.