gpt4 book ai didi

C - 存储 strtok 的结果?

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

所以我正在尝试将我的输入作为 file.txt,r 并且我必须在逗号上拆分字符串并保存 file.txtr 到单独的字符串中......但我真的很困惑该怎么做。我查了一下strtok这是我目前所拥有的:

 char buffer[256];
char filename[2][40];
char operation[20];
n = read(sock,buffer,255); //read the message from the client into buffer
char cinput[300];
strcpy(cinput,buffer);//now cinput has the whole thing

char *token;

token = strtok(cinput,",");

while(token)
{
printf("%s\n",token);
token = strtok(NULL,",");
}

但我很困惑......一旦解析,我如何将 file.txtr 存储为单独的字符串?

编辑:像这样的?

       char *token;

char *pt;

pt = strtok(cinput,","); //this will hold the value of the first one
strcpy(filename,pt);


token = strtok(cinput,",");
while(token)
{
//printf("%s\n",token);
token = strtok(NULL,",");
}
printf("%s\n",token); //this will hold the value of the second one

strcpy(operation,token);

printf("%s\n",operation);

最佳答案

您所需要的只是单独的指针。您不需要分配所有这些缓冲区或使用 strcpy()

只需将 strtok() 的返回值赋给多个 char * 指针。

类似于:

char *p1 = strtok("file.txt,r", ",");
char *p2 = strtok(NULL, ",");

关于C - 存储 strtok 的结果?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32857557/

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