c - 为什么 strtok() 没有正确迭代其 while 循环?

标签 c strtok

我正在尝试使用 strtok() 分解 C 中的字符串,并将获得的值分配给数组中结构的属性。

以下是字符串(预期输入)的样子:

steve 31516.john 31516.

我的代码(忽略变量定义):

while(fgets(line, sizeof(line), f) != NULL);

char* tok = strtok(line, ".");
while(tok != NULL){
    char* buf = strdup(tok);
    calendar[i].user = strtok(tok, " ");
    char* date = strtok(NULL, " ");
    calendar[i].date = atoi(date);
    tok = strtok(NULL, ".");
    free(buf);
    i++;
}

我想要的预期输出是这样的:

calendar[0].user = "steve"
calendar[0].date = 31516
calendar[1].user = "john"
calendar[1].date = 31516

然而,我得到的是:

calendar[0].user = "steve"
calendar[0].date = 31516

我遇到的问题是,这个循环似乎只发生一次,无论 strtok() 第一次运行的原始输入字符串有多长。它在循环内正确分配变量,但只运行一次。

最佳答案

以下代码应该实现您想要执行的操作。

#include <stdio.h>  // fopen(), fclose()
#include <stdlib.h> // exit(), EXIT_FAILURE
#include <string.h> // strtok()
#include <ctype.h>  // isspace()

int main( void )
{
    FILE * f = NULL;
    if( NULL == ( f = fopen( myFile, "r" ) ) )
    {
        perror( "fopen for myFile failed" );
        exit( EXIT_FAILURE );
    }

    // implied else, fopen successful


    #define MAX_LINE_LEN (1024)

    char line[ MAX_LINE_LEN ];
    while(fgets(line, MAX_LINE_LEN, f) != NULL) )
    {

        char* tok = strtok( line, ".");
        while( tok )
        {                       
            for( x = 0; !isspace(tok[x]); x++)
            {
                 calendar[].user[x] = tok[x];
            }

            x++; // step by the space

            calendar[i].date        = atoi( &tok[x] );

            tok = strtok(NULL, ".");
            i++;
        }
    }

请注意,上面的代码并不完整,而只是您需要执行的操作的示例。

关于c - 为什么 strtok() 没有正确迭代其 while 循环?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40371698/

相关文章:

c - 二维数组和指向指针的指针

c - 在 C 中使用 strtok 将日期字符串转换为整数

c++ - strtok、char** 和内存

c - C中String tokenizer的奇怪行为

c - 使用lua的lightuserdata注册定时器回调

c - 具有灵活数组成员的结构并为其分配内存

c++ - c 引用语义在调用者代码中不明确

c - 头文件中的结构声明错误

c - 使用可选参数格式 C/C++ 读取字符串

C - 另一个 strtok() 和 free() 问题