Reputation: 15
I'm trying to store 10 decimal numbers from a text file into an array. My problem is that it is skipping several numbers until it reaches the end of line.
I debugged the program by printing out the number of cycles the program took for reaching the end of the file, and resulted 10. And it is the correct value of how many numbers there are in the file. But when I display the element values of the array, only 5 numbers are there. When I compare the stored numbers with the text file numbers, It results that several numbers are being skipped.
Here is my code below :
#include <stdio.h>
#include <stdlib.h>
main(void)
{
FILE *inp; /* pointer to input file */
double item;
int cnt=0,y,d,i;
double array[300],swap;
/* Prepare files for input */
inp = fopen("C:/Users/infile.txt", "r");
/* Read each item */
while ( (fscanf(inp, "%lf", &item) == 1) && (!feof(inp)) ) {
array[cnt] = item;
cnt++;
}
for (int i = 0; i < cnt; i++)
{
printf("%lf\n",array[i]);
i++;
}
printf("%d",cnt);
fclose(inp); /* Close the files */
return (0);
}
-In the text file there are 10 double numbers ranging from 0 to 101 (ex 15.12563)
-The value for the cycle times of the while loop is 10 (cnt reaches 10)
-My code only stores 5 numbers instead of 10, which is skipping the rest 5 numbers, but it says it has reached the last value at line 10.
These are the values in the text file:
21.388000
12.372628
21.961366
85.616285
30.123001
30.271053
70.733982
35.867327
48.339462
82.459009
If I left some key information about my concern please ask. Thanks
Upvotes: 0
Views: 2501
Reputation: 1588
It is very simple problem
You store the values correctly. The error is in your printing cycle.
You increment the i
two times. Please delete the i++;
from second cycle.
I tested it, and it works well
Upvotes: 2