This question already has answers here:
Using strtok() in a loop in C?
                                
                                    (3个答案)
                                
                        
                                在11个月前关闭。
            
                    
我有一个看起来像这样的文本文件

44,12,4,5 2,45,3,1,2,45 6,77,5,3,5,44


我想使用strtok()将此文件分割成数字,然后将它们读入char **,并包含空格,这样

arr[0] = "44"
arr[1] = "12"
arr[2] = "4"
arr[3] = "5"
arr[4] = " "
arr[5] = "2"
...


到目前为止,这是我的代码:

    int i = 0;
    char line[6000], **arr = calloc(200, sizeof(char*)), *token = calloc(50, sizeof(char)), *token2 = calloc(8, sizeof(char));
    FILE* textFile = openFileForReading(); //Simple method, works fine.
    fgets(line, sizeof line, textFile);
    token = strtok(line, " ");
    token2 = strtok(token, ",");
    arr[i] = token2;
    while((token2 = strtok(NULL, ",")) != NULL)
    {
            i++;
            arr[i] = token2;
    }

    i++;
    arr[i] = " "; //adds the space once we're done looping through the "word"

    while((token = strtok(NULL, " ")) != NULL) //PROGRAM BREAKS HERE
    {
            token2 = strtok(token, ",");
            i++;
            arr[i] = token2;
            while((token2 = strtok(NULL, ",")) != NULL)
            {
                    i++;
                    arr[i] = token2;
            }
            i++;
            arr[i] = " ";
    }


在第二个while循环的开始,它从未执行。我确定这与将NULL参数传递到strtok有关,但是我不确定如何解决这个问题。如果您有任何意见,建议或批评,我很想听听。

最佳答案

strtok()在解析单个字符串时会在两次调用之间保持状态,因此不能像上面概述的那样使用它。

您有两种选择:要么使用可重入的strtok_r()并因此可以在编写时使用它,要么使用strtok()但首先将初始解析完成到以空格分隔的列表中,然后遍历结果字符串,处理它们是逗号分隔的数字。

关于c - 使用strtok两次将行分成“单词”,将“单词”分成较小的单词? ,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/55362678/

10-13 08:25
查看更多