Question

I'm trying to parse a string of the form:

structure: something 2 3 4 5 6 7 10 242 12

What I want is to print the integer values to a file. Now, I can use strtok and split the string based on spaces then strcmp the "structure:" and "something" words and not print them to the file. But those can be any word, so that would only work in this specific case. But it will always be of the form

<word1> <word2> 1 2 3 4 n

I tried to do something along the lines of using strchr to move the pointer to in front of the 2 and then use strtok on the subsequent string, which would allow me to only split the integers. I did something along the lines of:

char number[256];
char *pch;
// using strchr to navigate to second space in line,
// then use strtok to split numbers
pch = strchr(buf, ' ');
pch = strchr(pch + 1, ' ');

pch = strtok(buf, " ");
while (pch != NULL) {
    fprintf(outputFile, "%s\n", pch);
    pch = strtok(NULL, " ");
}

Clearly this doesn't work and just prints everything in the line. The attempt to increment the strchr is likely wrong as well, but I figured it would increment over the first space character it finds then find the second space (the one before 2). Then, I wanted to start from the pointer and strtok everything after that (though I'm just reassigning the pointer in this case).

So is it possible to get a string of everything after "something" and then run strtok on that?

Was it helpful?

Solution

Use pch instead of buf in

pch = strtok(buf, " ");

so update that line to

pch = strtok(pch, " ");
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top