我试图从文本文件中读取数据,并且试图将文本的每一行放在指向char
的指针中。我创建了char* ligne[nl];
,其中nl
是文本行的数量。尝试从文本文件中读取数据时发生的问题
问题是,当我尝试打印文本的每个ligne[]
时,我发现ligne
值只有最后一行而不是文本的所有行。 看看代码:
首先我的文件中的文本包含这些行:
mama
kaka
sasa
我使用的代码块C,而且代码:
int main(void) {
int i=0 ,k;
char *ligne[3] = {NULL}; // three char pointer that take each ligne
char word[25] = "";
FILE* file = fopen("dico.txt", "r");
if(file != NULL){
while (fgets(word, 25, file) != NULL){
ligne[i] = word;
i++;
}
// print each ligne of the file text
for(i =0 ; i < 3 ; i++){
printf("%s" , ligne[i]);
printf("\n");
}
}
return 0;
}
和结果打印ligne[i]
是:
sasa
sasa
sasa
代替:
mama
kaka
sasa
我在做什么错?
这是C还是C++?如果它是纯C代码,则删除C++标记。 – Slava
好吧,你对了 –