//Trying to read double values from each line of a file..and try to store them in arrays
//when i debugged,it doesnt do the parsing for the alldoubles
e.g
txt file consists
2.3,4.5,6.2,4.5
2.8,2.4,4.6,1.2,3.5
3.6,3.8,5.9,4.9,12.6,112.8
trying to put them in separate arrays
//CODE??
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
FILE *myFile;
unsigned int commas = 0;
//extracts the doubles from the file
double *parseLine(char *line)
{
unsigned int index = 0;
char *head;
double *values;
while(*head != '\0'){
if(*head == ',')
commas++;
head++;
}
//there is commas + 1, # of doubles in the string
head = line;
values = malloc(sizeof(double) * (commas + 1));
while(head != NULL){
head = strtok(line, ",");
values[index++] = atof(head);
}
return values;
}
int main()
{
char fileName[256];
double **allDoubles; //pointer 2 pointer 2 double
printf("Filename: ");
//fgets(fileName, sizeof(fileName), stdin);
scanf("%s",fileName);
//open file for reading
if((myFile = fopen(fileName, "r")) == NULL){
fprintf(stderr, "couldnt open %s", fileName);
return -1;
}
char buffer[BUFSIZ]; //going 2 hold the doubles as a String!!
unsigned int nlines = 0; //# lines
//we assume the file is ok, not corrupted data etc...
while(fgets(buffer, sizeof(buffer), myFile) != NULL)
if(strchr(buffer, '\n'))
nlines++;
unsigned int j = 0; //index to *allDoubles (i.e the list of doubles)
allDoubles = malloc(sizeof(double *) * nlines);
while(fgets(buffer, sizeof(buffer), myFile) != NULL)
allDoubles[j++] = parseLine(buffer);
printf("printing the doubles as double array ...\n");
//backwards I dont want 2 make more variables ...lol
// while(--nlines >= 0){
// while(--j >= 0)
for(int i=0;i<nlines;i++){
for(int k=0;k<j;k++){
printf("%f ", allDoubles[nlines][j]);
putchar('\n'); //new line
}
}
printf("FINISHED ...\n");
return 0;
}