0

I'm currently trying to split an array of chars that is assigned from reading in from a text file. right now I'm having troubles with delimiters and I don't know if I can have multiple. what I want to delimit is commas and spaces. Here is my code so far.

#include <stdio.h>
FILE * fPointer;
fPointer = fopen("file name", "r");
char singleLine[1500];
char delimit[] = 
int i = 0;
int j = 0;
int k = 0;


while(!feof(fPointer)){
    //the i counter is for the first line in the text file which I want to skip

    while ((fgets(singleLine, 1500, fPointer) != NULL) && !(i == 0)){
        //delimit in this loop
        puts(singleLine);

    }
    i++;
}

fclose(fPointer);

return 0;
}

What I've found so far is a way to delimit using a string of text that has shorthand for tabs and such e.g.

char Delimit[] = " /n/t/f/s";

then I would use this string in the strtok() method under the delimiter parameter

but this wont let me have a comma as a delimiter.

And the whole point of this is so I can start to assign the delimited strings into variables.

sample input: P1,2, 3 , 2

Any help or references is appreciated thanks.

Thorx99
  • 38
  • 1
  • 2
  • 9
  • `strtok`? Can you include a sample line from the textfile? What is the way 'you found so far'? – thelaws Jul 14 '16 at 17:21
  • @thelaws I added some more information if you need clarification let me know. – Thorx99 Jul 14 '16 at 17:25
  • 1
    You can use a `,` as a delimiter in `strtok`. There is an example of that here: http://www.cplusplus.com/reference/cstring/strtok/ – thelaws Jul 14 '16 at 17:27
  • so I'd just add a comma to the delimiter array. – Thorx99 Jul 14 '16 at 17:29
  • 1
    Unrelated, you had better hope that stream read really reaches EOF and avoids any stream *errors*, otherwise that outer loop never terminates. See [**this answer**](http://stackoverflow.com/a/26557243/1322972) for more information. – WhozCraig Jul 14 '16 at 17:40

1 Answers1

2

You can use a , as a delimiter in the strtok method.

I also think you meant to use \n\t for newlines and tabs (I don't know what /f/s is meant to represent).

Try using this:

char Delimit[] = " ,\n\t";

// <snip>

char * token = strtok (singleLine, Delimit);
while (token != NULL)
{
  // use the token here
  printf ("%s\n",token);

  // get the next token from singleLine
  token = strtok (NULL, Delimit);
}

That would transform your sample input P1,2, 3 , 2 into:

P1
2
3
2
thelaws
  • 7,991
  • 6
  • 35
  • 54
  • The problem with the `strtok()` approach is the potentially incorrect interpretation of sequences of adjacent delimiters: `P1,,,2,3,2` would produce the same output, empty values cannot be parsed using `strtok`. – chqrlie Jul 14 '16 at 20:27