Hi,
I have a txt file (attached) that I am attempting to read data from and store into an array. The data has headers and I am having trouble skipping the headers and only reading the data. What is the best way to go about this?
Thanks.
Hi,
I have a txt file (attached) that I am attempting to read data from and store into an array. The data has headers and I am having trouble skipping the headers and only reading the data. What is the best way to go about this?
Thanks.
What have you tried? Do you have any code that you can show?
My advice would be to use getline() to read the first line then discard/no put the line into any use.
To me discarding the header in the data.txt would probably be the best solution.Code:getline(arguments); //read the rest of the file.
I've tried the following, and it works when the headers are removed from the txt file. I'm just unsure how to modify it to work with headers.
Code:for(i=0; i<BUFSIZE; ++i) { if(fscanf(f, "%f,%f,%f,%f", &x[i][0], &x[i][1], &x[i][2], &x[i][3]) != 4) break; n++; } fclose(f); for(i=0; i<n; ++i){ printf("[ %f%f%f%f ]\n", x[i][0], x[i][1], x[i][2], x[i][3]); }
Probably the easiest thing to do is to use fgets instead of fscanf
The attempt to sscanf the header line will fail, but you've read it from the file.Code:char buff[BUFSIZ]; while ( fgets(buff, BUFSIZ, f) ) { if(sscanf(buff, "%f,%f,%f,%f", &x[n][0], &x[n][1], &x[n][2], &x[n][3]) == 4) n++; }
If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
If at first you don't succeed, try writing your phone number on the exam paper.
That worked perfectly, thank you!