c - 如何将从文件读取的strtok令牌添加到数组中?
问题描述
int main(){
FILE *file;
char line[100];
char name[26],code[4],donator[10],shipment[10], quantity[10];
int count = 0;
file = fopen("donation.txt","r");
if(!file){
printf("File does not exist!");
return 1;
}
while (!feof(file)){
fgets(line,100,file);
count++;
}
char *list[count][5];
memset(list,0,sizeof(list));
fseek(file,0,SEEK_SET);
count=0;
int count2=0;
char dtm[sizeof(line)];
while (!feof(file)){
fgets(line,100,file);
if (count>0){
strcpy(dtm,line);
printf("%s",dtm);
count2=0;
for(char *p = strtok(dtm,"|");p ; p=strtok(NULL,"|")){
printf("\n %d %s",count2,p);
list[count-1][count2]=p;
printf("\n%s",list1[count-1][count2]);
count2++;
}
}
count++;
}
for(int i =0; i<count-1 ;i++){
for(int k=0;k<count2;k++)
printf("\n%d %d %s",i,k,list[i][k]);
}
fclose(file);
return 0;
}
.
Contactless Thermommeter | CT | Japan | 1 | 1
Hand Sanitizer | HS | USA | 1 | 1
Face Mask | FM | China | 1 | 1
Surgical Mask | SM | China | 1 | 1
Oxygen Mask | OM | Saudi Arabia | 1 | 1
for 循环的预期输出片段:
0 0 Contactless Thermometer<br/>
0 1 CT<br/>
0 2 Japan<br/>
0 3 1<br/>
0 4 1<br/>
1 0 Hand Sanitizer<br/>
1 1 HS<br/>
1 2 USA<br/>
1 3 1<br/>
1 4 1<br/>
for 循环的输出片段:
0 0 Oxygen Mask<br/>
0 1 OM<br/>
0 2 Saudi Arabia<br/>
0 3 1<br/>
0 4 1<br/>
1 0 Oxygen Mask<br/>
1 1 OM<br/>
1 2 Saudi Arabia<br/>
1 3 1<br/>
1 4 1<br/>
在我的大学预科课程中学习 Python 后,我刚开始使用 C,如果有人能指导我了解我的代码出了什么问题,我将非常感激。在文件读取过程中,我使用strtok将txt文件中的行分解并存储在中list[i][k]
,如How to store tokens(strtok) in a pointer on an array中所示。它显示了预期的值,但在下一个 for 循环中,list[i][k]
仅显示了最后一组值,如下图所示。
解决方案
好的,代码有点乱,你只是想把你的文件映射到一个二维数组中。
有几个麻烦:
if (count>0){
为什么 ?您希望数组中的每一行都包含在内,不要跳过第一行。
list[count-1][count2]=p;
跳过-1。它与那里无关。
list[count-1][count2]=p;
是的,同一行有两个问题。
您在数组中分配了一个将更改的字符串上的指针。和指针别名。strtok 返回一个指向实际字符串的指针。它不会重新分配内存。
解决方案是简单地对您的字符串进行 strdup,因此它有一个新的内存,不会在下一个循环周期中更改。
list[count][count2] = strdup(p);
不要忘记稍后释放它。不要忘记检查您的 strdup 是否失败:)
其他说明:您有未使用的变量。换行符保留在字符串中的最后一个标记中。您可能想要删除它。
推荐阅读
- javascript - vscode中的节点调试
- java - 未将变量(请求属性)传递给 JSP EL 标记
- javascript - 重新渲染时组件闪烁
- windows - 递归地重命名特定目录中的文件以具有父级的名称
- git - 为什么heroku在部署反应应用程序时给出错误代码H81
- python - 我需要从这个循环的结果中提取邮政编码。
- c# - 具有多个文件附件列的 Datagridview
- python - 使用 Anaconda/Miniconda Python 在 Atom 包(即 Autocomplete-Python)中设置 Python 可执行路径
- swift - 如何在swift4中的字典中获取“数组中的键”的值
- html - 对象拟合未按预期执行