I am reading data from a file, retrieving how many columns and rows I have ( data file ), everything of so far. Now I am trying to read the values one by one and store the values in to a 2D array (double). I get the values as char using getc but when I try to use atoi or atof to convert the values from char to double i get strange values.
double ther[j][number];
char c;
int tim=0,nther=0;
FILE *fp3 = fopen("data.txt", "r");
c = getc(fp3) ;
while (c!= EOF)
{
ther[tim][nther]=atoi(&c);
printf("%lf", ther[tim][nther]);
nther++;
c = getc(fp3);
if(nther==number)
{
tim++;
nther=0;
}
tim=0;
}
fclose(fp3);
any suggestion?… (i keep searching). Sorry well i have a file data.txt and this file has rows an columns of numbers:
1 2 3 4 5
6 7 8 9 10
So i need to store the data into a 2D array: Thanks to the answers i have some ideas like: use an string, then divide all values and stored every one of them. 1st line is string-> array[0][0], array[0][1], etc. Then move to the other row and do the same.
Until now i get some numeric values but none of them are stored at the data.txt.
#include <stdio.h>
int main(){
int j = 2;
int number = 5;
double ther[j][number];
double d;
int tim=0,nther=0;
FILE *fp3 = fopen("data.txt", "r");
while (fscanf(fp3, "%lf", &d)==1){
ther[tim][nther]=d;
printf("%g ", ther[tim][nther++]);
if(nther==number){
++tim;
nther=0;
printf("\n");
}
}
{
int r, c;
for(r=0;r<tim;++r){
for(c=0;c<number;++c){
printf("%f ", ther[r][c]);
}
printf("\n");
}
}
return 0;
}