[問題] 讀檔跟三維動態陣列

看板C_and_CPP (C/C++)作者 (逐夢)時間14年前 (2011/09/29 11:56), 編輯推噓3(3015)
留言18則, 4人參與, 最新討論串1/1
開發平台(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)

09/29 12:03, , 1F
你所有的data[x][y]都指向str 但是str的值會不斷改變
09/29 12:03, 1F

09/29 12:04, , 2F
至於檔案中第一個1被getc吃掉了
09/29 12:04, 2F

09/29 12:05, , 3F
我個人是建議 與其用多維陣列把自己搞亂 不如用class
09/29 12:05, 3F

09/29 12:19, , 4F
c string的觀念錯誤,回去查一下吧
09/29 12:19, 4F

09/29 12:20, , 5F
還有那行malloc是幹嘛的…
09/29 12:20, 5F

09/29 12:23, , 6F
再來,要寫c就寫c,要寫c++就c++,不要new和malloc混用
09/29 12:23, 6F

09/29 12:25, , 7F
stdio style和iostream style混用看了也很難過
09/29 12:25, 7F

09/29 12:25, , 8F
初學儘量不要東抄一點西抄一點
09/29 12:25, 8F

09/29 12:34, , 9F
我還真不太了解malloc是幹嘛的= =
09/29 12:34, 9F

09/29 12:35, , 10F
改看看好了 謝謝O_Q
09/29 12:35, 10F

09/29 12:39, , 11F
如果要寫C式的話,string等於字元陳列,不能這樣用等於的
09/29 12:39, 11F

09/29 12:40, , 12F
如果要寫C++式的話,不要搞這種三維陣列
09/29 12:40, 12F

09/29 12:40, , 13F
然後用string class而不要用char*
09/29 12:40, 13F

09/29 13:46, , 14F
好~ 謝謝~
09/29 13:46, 14F

09/29 14:00, , 15F
網路上東找西找還真的蠻雜的 回去翻書好了= =
09/29 14:00, 15F

09/29 15:00, , 16F
malloc那段是從另一個地方抄進來的吧?XD
09/29 15:00, 16F

09/29 15:47, , 17F
對阿XD
09/29 15:47, 17F

09/29 15:50, , 18F
東西都蠻模糊的= =
09/29 15:50, 18F
文章代碼(AID): #1EW-o3ZM (C_and_CPP)
文章代碼(AID): #1EW-o3ZM (C_and_CPP)