c - 将来自 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
任何帮助深表感谢!!
解决方案
字符串存储为字符数组char*
。由于您的数组customers
具有类型char**
,并且您想要访问customers[z][i]
类型为customers
must be的字符串char***
。从行字符串填充数组时,使用
p = strtok(line, " ");
while (p != NULL)
{
customers[z][i] = p;
i++;
p = strtok (NULL, " ");
}
一个问题将是malloc
因为您不知道每个字符串的确切长度。
推荐阅读
- c# - 如何使用 C# 在 Json 上的特定级别添加新属性
- neo4j - Node中找不到值时的回退遍历方法
- azure - PowerBI 访问 Azure SQL 数据库(PaaS)
- scikit-learn - resnet 实现 pytorch 的准确率和召回率是一样的
- python - AttributeError:“ec2.ServiceResource”对象没有属性“send_command”
- python - Python根据另一个数据框中的多个条件添加新列值
- excel - 根据新文件的列名组合两个excel文件
- python - 使用循环将数据输入到 sqlite3 数据库时出错
- sql - ORA-01722: 无效的数字行以逗号传输 VARCHAR2 TO_NUMBER 开头
- conv-neural-network - tensorflow conv2d 参数个数