我是學習 c 的新手,我正在嘗試讀取檔案并將資訊放入多維陣列 multiar 中。
并最終使用該多維陣列來創建結構
有藝術家和年份的標題和名稱。
我試圖讀取由 "," 分隔的檔案,并將每個字串放入 MD 陣列的不同行中。
但是當我最終列印出陣列時,我遇到了奇怪的垃圾。
我該如何解決這個問題?
file.text 就像
All Along the Watchtower,Bob Dylan,1968,Mercedes Benz,Janis Joplin,1971,Stairway to Heaven,Led Zeppelin,1971,
代碼是
int main(){
char str[255];
char* token;
char multiar[50][50];
FILE *fptr;
fptr = fopen("file.text" ,"r");
fgets(str, 100, fptr);
token = strtok(str, ",");
//so this token now has "All Along the Watchtower"
int i = 0,j;
while (token !=NULL){
int len = strlen(token);
for (j=0;j<len;j ){
multiar[i][j] = token[j];
}
token = strtok(NULL,",");
i ;
}
int s, t;
for (s=0;s<30;s ){
for (t=0;t<30;t ){
printf("%c",multiar[s][t]);
}
printf("\n-----\n");
}
}
但輸出是
All Along the Watchtower
-----
Bob Dylan
-----
19680?s????s????s????
-----
Mercedes Benz??LP??s?
-----
Janis Joplin???@-???
-----
1971 ? ? x0???
-----
Stairway to Heaven ? ?
-----
Led Zepp???-????Q
-----
??q???b x0???
-----
???(?? ?@?
-----
P? ?v ?b
-----
?Zx0???`.????
-----
-----
-----
-----
-----
?/????? ?
-----
(?i???/??? ?
-----
1???0???>2 ?1
-----
-----
R? ??0???h?
-----
?1
-----
9?/ ?@?
-----
1P@2
-----
$
-----
?????1
-----
?&?; ?
-----
????
-----
-----
`?p5???x5???
-----
但我希望輸出像
All Along the Watchtower
-----
Bob Dylan
-----
1968
-----
Mercedes Benz
-----
Janis Joplin
-----
1971
-----
Stairway to Heaven
-----
Led Zepp
-----
1971
-----
uj5u.com熱心網友回復:
您的代碼有兩個問題:
- 您不會
NUL終止保存到multiar. - 您
multiar在輸出中任意回圈字符,而不是回圈保存在那里的有效資料。
#include <stdio.h>
#include <string.h>
int main(){
char str[255] = "All Along the Watchtower,Bob Dylan,1968,Mercedes Benz,Janis Joplin,1971,Stairway to Heaven,Led Zeppelin,1971,";
char* token;
char multiar[50][50];
token = strtok(str, ",");
//so this token now has "All Along the Watchtower"
int i = 0,j;
while (token !=NULL){
int len = strlen(token);
// could use strcpy, strncpy, memcpy, etc here instead of manually
// copying each character.
for (j=0;j<len;j ){
multiar[i][j] = token[j];
}
// NUL terminate the string here
multiar[i][j] = '\0';
token = strtok(NULL,",");
i ;
}
int s, t;
// loop over i, that's how many words are in your array
for (s=0;s<i;s ){
int len = strlen(multiar[s]);
// loop over the string length for each string at multiar[i]
// could forgo this loop entirely and just printf("%s", multiar[s]) instead
for (t=0;t<len;t ){
printf("%c",multiar[s][t]);
}
printf("\n-----\n");
}
}
請注意,這里沒有檢查 上的越界訪問multiar,這是您應該實作的。
示范
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/318462.html
上一篇:我需要幫助獲取C中的檔案資訊
