Dear All,
I have a text file containing these lines:
12345
12
123
1234
123456
1234567890
123456789032453
1234567890724832445
12345.123456
12345.123
12.12
12
And I want to read them from c:\numbers.txt and store them into an array and then do some calculations, then save the results in another file(c:\results.txt).
I have wrote the following program for just reading lines of a file and store into an array:
#include <stdio.h>
#include <stdlib.h> /* required for atoi */
int main(void) {
int i=0;
double numbers[]={0};
char line[20]; /* declare a char array */
FILE *file; /* declare a FILE pointer */
file = fopen("c:\\numbers.txt", "r"); /* open a text file for reading */
while(fgets(line, 100, file)!=NULL) { /* keep looping until NULL pointer... */
printf("Lines of numbers.txt file are: %s", line);
numbers[i]=atoi(line); /* convert string to int */
i++;
}
for (i=0 ; i<sizeof(numbers) ; i++)
{ printf("\nThe number %d of %d is: %i", i+1,sizeof(numbers), numbers[i]); }
fclose(file);
return 0;
}
The first problem : the numbers are not correct in the array. it shows this output:
Lines of numbers.txt file are: 123
Lines of numbers.txt file are: 1234
Lines of numbers.txt file are: 123456
Lines of numbers.txt file are: 1234567890
Lines of numbers.txt file are: 123456789032453
Lines of numbers.txt file are: 1234567890724832445
Lines of numbers.txt file are: 12345.123456
Lines of numbers.txt file are: 12345.123
Lines of numbers.txt file are: 12.12
Lines of numbers.txt file are: 12
The number 1 of 8 is: 0
The number 2 of 8 is: 822096433
The number 3 of 8 is: 905972275
The number 4 of 8 is: 171258932
The number 5 of 8 is: 0
The number 6 of 8 is: -1266679808
The number 7 of 8 is: 2126512128
The number 8 of 8 is: -792723456
Another problem is that some times the two first lines of input file is not shown.
Please help me to solve the problems.
Thanks in Advance,
Mehdi