gpt4 book ai didi

c - 我需要从文本文件中读取一行逗号分隔的整数并将它们存储到数组中

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

我试过使用strtok函数,但我不知道如何使用它

这是我从网上看到的代码

FILE *ptr = fopen("testdoc.txt", "r");

char nums[100];

fgets(nums,100,ptr);
const char s[2] = ",";
char *token;
token =strtok (nums, s);
while( token != NULL )
{
printf( " %s\n", token );

token = strtok(NULL, s);
}

为什么我们在最后一行有 token = strtok(NULL,s)?以及如何将 token 获得的数字存储到数组中?非常感谢,请详细说明

最佳答案

来自 strtok引用

On a first call, the function expects a C string as argument for str, whose first character is used as the starting location to scan for tokens. In subsequent calls, the function expects a null pointer and uses the position right after the end of last token as the new starting location for scanning.

也就是strtok在内部存储位置。

获取 token 数量非常简单。没有奇迹。只需使用 counter 并在循环中递增它。

关于c - 我需要从文本文件中读取一行逗号分隔的整数并将它们存储到数组中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20299444/

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