我試圖從文本文件中讀取數據,並且試圖將文本的每一行放在指向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
好吧,你對了 –