Reputation: 1
I was wondering why it's keep on printing number 1 even though I got no number 1 in my file
The input file is: file.in
2
4
0 0 0 0
FILE *fp;
fp = fopen("file.in","r");
if(fp != NULL)
{
fscanf(fp, "%d\n", &noOfPuzzles);
fscanf(fp, "%d\n", &dimensionOfBoard);
int position[dimensionOfBoard];
int value[dimensionOfBoard];
for(i = 0 ; i< dimensionOfBoard; i++)
{
position[i] = fscanf(fp, "%d ", &value[i]);
}
}
printf("No. of Puzzles: %d\n",noOfPuzzles);
printf("Dimension of Board: %d\n",dimensionOfBoard);
for(i = 0 ; i< dimensionOfBoard; i++)
{
printf("%d ",position[i]);
}
The output is always like this:
No. of Puzzles: 2
Dimension of Board: 4
1 1 1 1
How come that it keeps on printing number '1'? Thank you
Upvotes: 0
Views: 53
Reputation: 588
You are assigning the return value of fscanf()
to position[i]
, which returns how many values it successfully populated or −1 if an error occured.
Rather, you need to use the values[i]
array to print the zeroes you read from file.
Upvotes: 0
Reputation: 1404
You are printing out position[i], which you have set to the return value of fscanf. Fscanf places the read value into its second argument in this case and returns the number of characters read. You need to print out values[i] instead.
Upvotes: 0
Reputation: 93172
Your usage of fscanf
is incorrect. fscanf
returns the number of items it successfully scanned, which is 1 item in your case, thus assigning 1
to every member of position
. I don't know what the purpose of the value
array is, but you could scan directly into position
like this:
fscanf(fp, "%d ", &position[i]);
Upvotes: 0
Reputation: 948
What you are doing is catching the return value of fscanf():
position[i] = fscanf(fp, "%d ", &value[i]);
You're storing 1 in position[i] because fscanf() returns 1 to indicate that it populated 1 value - you're reading the actual value to value[i] then outputting the value in position[i]
fscanf(fp, "%d", &position[i]);
Will work, output the values of the value[] array in the last loop.
Upvotes: 2