[問題] 讀檔

看板C_and_CPP作者 (XD)時間14年前 (2010/02/06 22:07), 編輯推噓3(309)
留言12則, 5人參與, 最新討論串2/2 (看更多)
檔案是a.txt 裡面的格式是 小明 5000 50 20 30 小華 4500 40 70 80 typedef struct man_s { char *name; //名字 int pay; int par1; int par2; int par3; } man_t; 然後我有宣告一個structure 希望把檔案裡面的東西讀到結構裡 可是再讀到pay時, name會跟pay相同 請問這是哪邊有問題? man_t man[2]; FILE *FP; char str[100]; int i,j,tmp,count = 0; if((FP = fopen("a.txt", "r+b")) == NULL){ printf("File : %s 並不在目前的資料夾下 請重新確認!\n","a.txt"); system("pause"); exit(0); } for(i=0;fscanf(FP,"%s",str)!=EOF;i++){ if(i%5 == 0){ man[count].name = str; }else if(i%5 == 1){ tmp = atoi(str); man[count].pay = tmp; }else if(i%5 == 2){ tmp = atoi(str); man[count].var1 = tmp; }else if(i%5 == 3){ tmp = atoi(str); man[count].var2 = tmp; }else{ tmp = atoi(str); man[count].var3 = tmp; count++; } printf("%s\n",man[count].name); printf("%d\n",man[count].pay); printf("%d\n",man[count].var1); printf("%d\n",man[count].var2); printf("%d\n",man[count].var3); system("pause"); } -- ※ 發信站: 批踢踢實業坊(ptt.cc) ◆ From: 180.177.2.215

02/06 22:11, , 1F
因為name指向的位址 拿去存pay的內容了 應該吧 @@
02/06 22:11, 1F

02/06 22:11, , 2F
用strcpy應該就避掉了 @@
02/06 22:11, 2F

02/06 22:12, , 3F
man[count].name = str; 這邊用strcpy嗎?
02/06 22:12, 3F

02/06 22:32, , 4F
上面那行只是把str的位址 assign 給name指標, 根本沒做
02/06 22:32, 4F

02/06 22:33, , 5F
到copy字串的功能.
02/06 22:33, 5F

02/06 22:35, , 6F
話說, struct裡的name只是指標, 你就算想strcpy也沒有空
02/06 22:35, 6F

02/06 22:35, , 7F
間放; 簡單的作法就是開一個一定夠大放name的array而不
02/06 22:35, 7F

02/06 22:35, , 8F
要用pointer, 這樣就可以strcpy了; 麻煩一點就每次name
02/06 22:35, 8F

02/06 22:36, , 9F
讀回來都算字串長度來malloc(), 這樣name可以繼續用
02/06 22:36, 9F

02/06 22:36, , 10F
pointer, 但還是一樣要strcpy才行@_@"
02/06 22:36, 10F

02/06 22:45, , 11F
OK了 感謝幫忙
02/06 22:45, 11F

02/09 18:30, , 12F
用 malloc();
02/09 18:30, 12F
文章代碼(AID): #1BRNUJdE (C_and_CPP)
討論串 (同標題文章)
文章代碼(AID): #1BRNUJdE (C_and_CPP)