arrays - 如何将字符串分成几部分并存储到C中的数组中?
问题描述
我有一个文本文件,其中列出了一些杂货和有关它们的信息。看起来像这样:
Round_Steak 1kg 17.38 18.50
Chicken 1kg 7.21 7.50
Apples 1kg 4.25 4.03
Carrots 1kg 2.3 2.27
这是我使用的代码,它允许我引用每一行:
#include <stdio.h>
#include <string.h>
#define Llimit 100
#define Rlimit 10
int main()
{
//Array Line gets each line from the file by setting a limit for them and printing based on that limit.
char line[Rlimit][Llimit];
FILE *fp = NULL;
int n = 0;
int i = 0;
fp = fopen("food.txt", "r");
while(fgets(line[n], Llimit, fp))
{
line[n][strlen(line[n]) - 1] = '\0';
n++;
}
printf("%s", line[1]);
fclose(fp);
return 0;
}
例如,如果我打印 line[1],我将得到“Chicken 1kg 7.21 7.50”。然而,我需要做的是将每个字符串分成各自的部分。因此,如果我调用 line[1][0] 之类的东西,结果我只会得到“Chicken”。我已经尝试在一些 for 循环和其他类似的东西中使用 strtok(line[i], " ") ,但我真的很困惑如何将它应用到这段代码中。
解决方案
你可以写一个函数(str_to_word_array)这是我的str_to_word_array func https://github.com/la-montagne-epitech/mY_Lib_C/blob/master/my_str_to_word_array.c 它需要一个字符串和一个分隔符(“”对于你的情况) ,您必须将结果存储在 char ** 中,就像这样:
char *line; // type of the element
char separator // type of the element
char **tab = my_str_to_word_array(line, separator);
推荐阅读
- python - 防止 NaN 成为数据框枢轴中的索引和列
- swift - 快速排序复杂数组
- c# - C#如何在10分钟后停止定时器
- php - 我想从 PHP 中的字符串 html 中提取数据
- android - 将方向设置为 0 并且仍然在 Android 的 ImageView 中获取旋转的图像
- python - Python Selenium 中途更改 Chrome 选项
- mfc - 为什么 MFC Ado 应用程序不能在另一台计算机上运行?
- perl - 将匿名哈希插入匿名哈希以循环计数
- docker - 使用 docker compose 抑制 docker 网络以实现测试执行隔离
- javascript - 为什么我的过滤器没有按预期工作?