我有一个像这样的文本文件:
word 1;word 2;word 3;word 4
word 5;word 6;word 7;word 8
word 9;word 10;word 11;word 12
word 13;word 14;word 15;word 16
我想将此文件导出到C中的2d字符串数组中。这是我的代码:
char* orders[LineCounter][4];
int i = 0, j;
f = fopen("test.txt","r");
printf("Inside the loop\n");
while (getline(&line, &len, f) != -1) {
j = 0;
char* token = strtok(line,";\n");
while (token != NULL){
orders[i][j] = token;
printf("%s\n", orders[i][j]);
token = strtok(NULL,";\n");
j++;
}
i++;
}
printf("\n\nOutside the loop\n");
for (int k=0;k<LineCounter;k++){
for (int l=0;l<4;l++){
printf("%s ", orders[k][l]);
}
printf("\n");
}
fclose(f);
如您所见,我两次打印了数组的内容。一次在strtok循环内,一次在所有操作完成之后。第一次一切都可以正常打印,但是当我解析完文件后打印数组时,内容会像这样混乱:
Inside the loop
word 1
word 2
word 3
word 4
word 5
word 6
word 7
word 8
word 9
word 10
word 11
word 12
word 13
word 14
word 15
word 16
Outside the loop
word 13 4 15
word 13 4 15
word 13
word 13 word 14 word 15 word 16
您可以看到部分内容为空或“单词”被截断。我想念什么吗?