[問題] 二維陣列如何存入.txt檔

看板C_and_CPP (C/C++)作者時間16年前 (2009/12/27 19:28), 編輯推噓2(2014)
留言16則, 5人參與, 最新討論串1/2 (看更多)
請問要如何把二維陣列存入.txt檔內 開發平台:Microsoft Visual C++ 6.0 以下是我寫的程式片段: //印出陣列(結果正確) for(int i=0;i<121;i++){ for(int j=0;j<5;j++){ printf("%d,",pos_table[i][j]); } printf("\n"); } //將陣列資料寫入output.txt(結果錯誤) FILE *fptr; using namespace std; if(fptr!=NULL){ string pos_table[120][5]; fptr=fopen("C:\\Documents and Settings\\andy\\桌面\\output.txt","w"); printf("**************************************output.txt********************************"); for(i=0;i<120;i++){ for(int j=0;j<5;j++){ fprintf(fptr, "%d,",pos_table[i][j].c_str()); } fprintf(fptr,"\n"); } fclose(fptr); printf("\r\n檔案拷貝完成!!\r\n"); } else{ printf("\r\n開啟檔案失敗!!\r\n"); } 但結果在txt檔裡面全都是(4358200,4358200,4358200,4358200,4358200,)×120行, 不曉得是哪裡出了問題? 請各位高手幫忙解答一下,謝謝~ ※ 編輯: arno855268 來自: 123.192.109.141 (12/27 19:30)

12/27 19:38, , 1F
為什麼你印在螢幕上的print變數跟要輸出到檔案的 不同?
12/27 19:38, 1F

12/27 19:38, , 2F
拿掉.c_str()看看
12/27 19:38, 2F

12/27 19:48, , 3F
試過囉!拿掉.c_str()
12/27 19:48, 3F

12/27 19:49, , 4F
結果變成-858993460
12/27 19:49, 4F

12/27 19:50, , 5F
-858993460,-858993460,-858993460,-858993460,-858993
12/27 19:50, 5F

12/27 19:56, , 6F
%d string ?
12/27 19:56, 6F

12/27 20:05, , 7F
我用%s,但是會跳出錯誤訊息:
12/27 20:05, 7F

12/27 20:06, , 8F
Unhandled exception in network.exe:0xC0000005:
12/27 20:06, 8F

12/27 20:07, , 9F
Accedd Violation
12/27 20:07, 9F

12/27 20:14, , 10F
如果我換成int pos_table[120][5]; 用%d,輸出結果還是:
12/27 20:14, 10F

12/27 20:15, , 11F
-858993460,-858993460,-858993460,-858993460,-858993
12/27 20:15, 11F

12/27 21:00, , 12F
%s是給char[]用的 string要加上c_str()
12/27 21:00, 12F

12/27 21:07, , 13F
不好意思,其實我在全域變數定義過:
12/27 21:07, 13F

12/27 21:07, , 14F
int pos_table[120][5]={-1};
12/27 21:07, 14F

12/27 21:08, , 15F
所以不是string
12/27 21:08, 15F

12/27 23:43, , 16F
請問一下原po 你的pos_table[120][5]型態究竟是要用哪一種?
12/27 23:43, 16F
文章代碼(AID): #1BDqJBmW (C_and_CPP)
文章代碼(AID): #1BDqJBmW (C_and_CPP)