1

I'm working on some code that takes in a file and then does stuff with those numbers, and I need to put the data into it's own array set. I've done it using fscanf, but now I'm required to do it with strtok. I could do it if each thing was going into the same array, but I don't know how to get each item in it's own array.

TL:DR; I need to do this

/*************************************************************************

3/25/2015
This program takes in a file of the format
    PART,2.000,-1,0.050,V
    PART,0.975,-1,0.025,V
    PART,3.000,+1,0.010,F
    GAP,0.000,0.080
does the tolerance analysis
**************************************************************************/
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <string.h>
int main()
{
    FILE *FTIN;
    FTIN = fopen ("tin.txt", "r");
    float nom[100], tollerance[100];
    int SIGNS[100];
    char V_F[100];
    int status, i, x;
    float Act_Gap, Act_Tollerance, Maximum_Gap, Minnimum_Gap, Spec_Minnimum, Spec_Maximum;

    if (FTIN == NULL){    //file empty/broken error

            printf("ERROR\n");
            return (1);
        }
    else{
        for (i=0; status != EOF; i++){  //reads until EoF, even though some guy on stackoverflow taught me it's bad
            status = fscanf(FTIN,"PART,%f,%d,%f,%c\n", &nom[i], &SIGNS[i], &tollerance[i], &V_F[i]); //scans for a part
            status = fscanf(FTIN, "GAP,%f,%f\n", &Spec_Minnimum, &Spec_Maximum);  //scans for a gap
            }

Using strtok.

  • 1
    Could you at least try to use strtok reading [any manual page](http://linux.die.net/man/3/strtok) – dvhh Mar 29 '15 at 19:27
  • 1
    I've been reading manual pages for days, I'm just stupid. – Felix Amore Mar 30 '15 at 02:44
  • using google could get you some [examples](http://www.tutorialspoint.com/c_standard_library/c_function_strtok.htm) like [this one](http://fresh2refresh.com/c/c-strings/c-strtok-function/), [reading file line by line](http://stackoverflow.com/questions/3501338/c-read-file-line-by-line) has been asked on stackoverflow – dvhh Mar 30 '15 at 03:06

1 Answers1

1

All you have to do is read one line at a time (e.g. using fscanf(FTIN, "%s", line)), then split the line using strtok using a comma as the token and finally iterate the tokens and convert each of them to relevant field.

Amnon Shochot
  • 8,998
  • 4
  • 24
  • 30