从双指针“2d数组”中的strtok()存储标记

时间:2022-05-31 21:37:14

Input file:

输入文件:

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

Code:

码:

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]);

So essentially, I am reading each line of txt input file, breaking it down into tokens with strtok(), and store them into a double pointer(customers) that functions like a 2d array, but after the while loop exits, I can’t access the each individual token within this “2d array”, I can access the whole line of it with

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

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

outputs:
s0301

but this only prints the first character of each token rather than the whole string. How can I access the full tokenised string with for example like this

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

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

Any help is much appreciated!!

任何帮助深表感谢!!

1 个解决方案

#1


0  

A string is stored as a character array char*. Since your array customers has the type char** and you want to access the string with customers[z][i] the type of customers must be char***. When filling the array from a line string use

字符串存储为字符数组char *。由于您的阵列客户具有char **类型,并且您想要访问客户[z] [i]的字符串,因此客户类型必须是char ***。从行字符串填充数组时使用

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

A problem will be the malloc since you don't know the exact length of each string.

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

#1


0  

A string is stored as a character array char*. Since your array customers has the type char** and you want to access the string with customers[z][i] the type of customers must be char***. When filling the array from a line string use

字符串存储为字符数组char *。由于您的阵列客户具有char **类型,并且您想要访问客户[z] [i]的字符串,因此客户类型必须是char ***。从行字符串填充数组时使用

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

A problem will be the malloc since you don't know the exact length of each string.

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