在移动strchr指针后使用strtok

Using strtok after moving strchr pointer

本文关键字:strtok 指针 移动 strchr      更新时间:2023-10-16

我试图解析一个字符串的形式:

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

我想要的是将整数值打印到文件中。现在,我可以使用strtok并根据空格分割字符串,然后对"structure:"answers"something"进行字符串分割,而不将它们打印到文件中。但是它们可以是任何单词,所以这只适用于这个特定的情况。但它的格式总是

<word1> <word2> 1 2 3 4 n

我尝试使用strchr将指针移动到2的前面,然后在随后的字符串上使用strtok,这将允许我只拆分整数。我做了如下操作:

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, "%sn", pch);
    pch = strtok(NULL, " ");
}

显然这不起作用,只是打印该行中的所有内容。尝试增加strchr也可能是错误的,但我认为它会在它找到的第一个空格字符上增加,然后找到第二个空格(2之前的那个)。然后,我想从指针开始并删除之后的所有内容(尽管在这种情况下我只是重新分配指针)。

那么,是否有可能在"某事"之后得到一个字符串,然后运行strtok ?

pch代替buf

pch = strtok(buf, " ");

所以将这行更新为

pch = strtok(pch, " ");