问题
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.
回答1:
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
来源:https://stackoverflow.com/questions/38380419/splitting-a-string-using-multiple-delimiters-in-c