【发布时间】:2020-10-17 23:09:40
【问题描述】:
我有一个文本文件,其中列出了一些杂货和有关它们的信息。看起来像这样:
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], " "),但我真的很难将它应用到这段代码中。
【问题讨论】:
-
您应该显示您尝试过的代码以及使用它时发生的情况。
strtok是一个“狡猾”的野兽。 -
我会尝试追溯代码,并编辑帖子。