為什麼這篇Malloc 多維 陣列鄉民發文收入到精華區:因為在Malloc 多維 陣列這個討論話題中,有許多相關的文章在討論,這篇最有參考價值!作者stanley0412 (逐夢)看板C_and_CPP標題[問題] 讀檔跟三維動態陣列時間Thu...
開發平台(Platform): (Ex: VC++, GCC, Linux, ...)
Dev C++
問題(Question):
讀TXT檔少讀半格,冏!!
三維陣列讀檔那邊,印出來確實是六次,每次顯示的數值也不一樣,
但最後印出來的全都一樣..不知道是哪裡有問題..
餵入的資料(Input):
123 integer
234 string
532 float
預期的正確結果(Expected Output):
印在螢幕上的是
the element of data[0][0] is 123
the element of data[0][1] is integer
the element of data[1][0] is 234
the element of data[1][1] is string
the element of data[2][0] is 532
the element of data[2][1] is float
123 integer
234 string
532 float
錯誤結果(Wrong Output):
the element of data[0][0] is 23
the element of data[0][1] is integer
the element of data[1][0] is 234
the element of data[1][1] is string
the element of data[2][0] is 532
the element of data[2][1] is float
float float
float float
float float
程式碼(Code):(請善用置底文網頁, 記得排版)
讀檔與動態陣列的部分:
FILE *fptr;
fptr = fopen("test.txt","r");
if(fptr==NULL)
cout<<"error opening file\n";
char ***data = new char **[3];
for(int i = 0;i<3;i++){
data[i] = new char *[2];
for(int j = 0;j<2;j++)
data[i][j] = (char*)malloc(sizeof(char));
}
把檔案的東西塞入陣列裡:
char ch;
char str[1000];
int x = 0;
int y = 0;
while((ch=getc(fptr))!=EOF){
fscanf(fptr,"%s",str);
int j = strlen(str);
if(j!=0){
data[x][y] = str;
cout<<"the element of data["<<x<<"]["<<y<<"] is "<<data[x][y]<<endl;
y++;
if(y==2){
x++;
y=0;
}
}
if(x==3)
break;
}
顯示出來的部分:
for(int x = 0;x<3;x++){
for(int y = 0;y<2;y++){
cout<<data[x][y]<<" ";
}
cout<<endl;
}
補充說明(Supplement):
只是想寫個小程式測試小文件看看,所以才會把行、列寫死
TXT檔的編碼都試過了0.0a 還是不行Orz
--
※ 發信站: 批踢踢實業坊(ptt.cc)
◆ From: 140.109.196.209
※ 編輯: stanley0412 來自: 140.109.196.209 (09/29 12:01)