首页 > 解决方案 > 将来自 strtok() 的标记存储在双指针“二维数组”中

问题描述

输入文件:

s0 0 3 0 10
s1 0 6 0 20
s2 0 5 0 11
s3 0 6 0 20
s4 67 2 0 25
s5 5 4 0 1
s6 0 2 0 5
s7 0 4 0 28
s8 0 3 0 20
s9 45 5 0 6
s10 103 3 0 2

代码:

char ** customers;
char *p;
customers = (char **)malloc(50 * sizeof(char *));

for (int i = 0; i < 50; i ++)
{
    customers[i] = (char *)malloc(5 * sizeof(char *));
}

int z = 0;
while ((nread = getline(&line, &len, stream)) != -1)
{
    int i = 0;
    p = strtok (line, " ");

    while (p != NULL)
    {
        customers[z][i] = *p;
        i++;
        p = strtok (NULL, " ");
    }
    z++;

}
printf("%s\n", customers[0]);

所以本质上,我正在读取 txt 输入文件的每一行,用 strtok() 将其分解为标记,并将它们存储到一个双指针(客​​户)中,其功能类似于二维数组,但在 while 循环退出后,我可以t 访问这个“二维数组”中的每个单独的令牌,我可以访问它的整行

printf(“%s\n”, customers[0])

outputs:
s0301

但这只会打印每个标记的第一个字符,而不是整个字符串。如何访问完整的标记化字符串,例如这样

printf(“%s\n”, customers[0][0])
printf(“%s\n”, customers[0][1])
printf(“%s\n”, customers[0][2])
printf(“%s\n”, customers[0][3])
printf(“%s\n”, customers[0][5])

outputs:
s0
0
3
0
10

任何帮助深表感谢!!

标签: cpointersmultidimensional-arraymallocstrtok

解决方案


字符串存储为字符数组char*。由于您的数组customers具有类型char**,并且您想要访问customers[z][i]类型为customersmust be的字符串char***。从行字符串填充数组时,使用

p = strtok(line, " ");
while (p != NULL)
{
    customers[z][i] = p;
    i++;
    p = strtok (NULL, " ");
}

一个问题将是malloc因为您不知道每个字符串的确切长度。


推荐阅读