gpt4 book ai didi

c++ - 移动 strchr 指针后使用 strtok

转载 作者:太空宇宙 更新时间:2023-11-04 07:18:41 25 4
gpt4 key购买 nike

我正在尝试解析以下形式的字符串:

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

我想要的是将整数值打印到文件中。现在,我可以使用 strtok 并根据空格拆分字符串,然后对“structure:”和“something”字词进行 strcmp,而不是将它们打印到文件中。但是那些可以是任何词,所以这只适用于这种特定情况。但它将始终是

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

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

那么是否有可能在“something”之后获取所有内容的字符串,然后在其上运行 strtok?

最佳答案

中使用 pch代替 buf
pch = strtok(buf, " ");

因此将该行更新为

pch = strtok(pch, " ");

关于c++ - 移动 strchr 指针后使用 strtok,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22733761/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com