嗨,這里需要一點幫助。我有一個包含 5 行的檔案,我想將這些行放入一個型別陣列中,char *lines[5];但我無法弄清楚為什么以下內容不起作用。
#include <stdio.h>
#include <string.h>
int main(void) {
FILE *fp = fopen("name.txt", "r");
char *str;
char *list[5];
int i = 0;
while (fgets(str, 100, fp) != NULL) // read line of text
{
printf("%s", str);
strcpy(list[i], str);
i ;
}
}
uj5u.com熱心網友回復:
正如評論者所說,您需要創建一個足夠大的陣列(只不過是記憶體中的一個空間)來存盤您的字串。以下是解決問題的一種方法,請注意注釋:
#include <stdio.h>
#include <string.h>
int lines(FILE *file); //try to format the code according to some standard
int main(void) {
FILE *fp = fopen("name.txt", "r");
char list[5][100]; //make sure you allocate enough space for your message
// for loop is more elegant than while loop in this case,
// as you have an index which increases anyway.
// also, you can make sure that files with more than 5 lines
// do not break your program.
for(int i = 0; i<5 ; i )
{
if(fgets(list[i], 100, fp) == NULL){
break;
}
//list[i] is already a string, you don't need an extra copy
printf("%s", list[i]);
}
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/430161.html
