[問題] 程式初學者遇到一些字元讀檔的問題

看板C_and_CPP作者 (玟)時間12年前 (2012/02/20 11:19), 編輯推噓1(105)
留言6則, 4人參與, 最新討論串1/1
開發平台(Platform): (Ex: VC++, GCC, Linux, ...) VC++ 問題(Question): 各位大大好,小妹是程式初學者>'< 最近在讀檔時遇到一些瓶頸...不知道可不可以請各位幫我看一下 以下是讀檔的範例: GRID* 23165 3.333683E+002 1.810428E+002 * 5.449939E+0010 GRID* 23166 3.333683E+002 1.810428E+002 * 5.599939E+0010 GRID* 23167 3.317019E+002 1.810428E+002 * 5.449939E+0010 GRID* 23168 3.317019E+002 1.810428E+002 * 5.599939E+0010 說明: 1.以上的讀檔一行有80個字元,我想以第一欄先讀8個字元,而中間16字元方式讀取 →讀檔字元格式如下 8 16 16 16 16 8(總共80字元) 2.接著繼續讀下一行 →讀檔字元格式如下 8 16 如果完全正確讀成功的話,則會變成以下的字串 GRID* 23165 3.333683E+002 1.810428E+002 5.449939E+001 GRID* 23166 3.333683E+002 1.810428E+002 5.599939E+001 GRID* 23167 3.317019E+002 1.810428E+002 5.449939E+001 GRID* 23168 3.317019E+002 1.810428E+002 5.599939E+001 程式碼(Code):(請善用置底文網頁, 記得排版) 附上我的code,我是在這個function中出現問題的(有時候會當掉,不知道為什麼) 而且code也寫得太冗長了>"<不知道是否還有可以改進的方式... char *fp=NULL,szTemp[256]; int intTemp=0; char strbuftemp[256]="",ilinetemp[256]=""; int count=0; int strLength=0,iline=0,iscale=0; if(strstr(strbuf,"GRID*")!=NULL) { for(int jj=0;jj<8;jj++) { strbuftemp[jj]=strbuf[count]; count++; } strbuftemp[8]='\0'; sscanf(strbuftemp,"%s",&intTemp); // NodeID for(int jj=0;jj<16;jj++) { strbuftemp[jj]=strbuf[count]; count++; } strbuftemp[16]='\0'; sscanf(strbuftemp,"%d",&i[0]); for(int jj=0;jj<16;jj++) { strbuftemp[jj]=strbuf[count]; count++; } strbuftemp[16]='\0'; sscanf(strbuftemp,"%s",&intTemp); // X for(int jj=0;jj<16;jj++) { strbuftemp[jj]=strbuf[count]; count++; } strbuftemp[16]='\0'; sscanf(strbuftemp,"%lf",&d[0]); // Y for(int jj=0;jj<16;jj++) { strbuftemp[jj]=strbuf[count]; count++; } strbuftemp[16]='\0'; sscanf(strbuftemp,"%lf",&d[1]); fp = fgets(szTemp,255,file_); char strbuftemp[256]="",ilinetemp[256]=""; int count=0; int strLength=0,iline=0,iscale=0; for(int jj=0;jj<8;jj++) { strbuftemp[jj]=strbuf[count]; count++; } strbuftemp[8]='\0'; sscanf(strbuftemp,"%s",&intTemp); // Z for(int jj=0;jj<16;jj++) { strbuftemp[jj]=strbuf[count]; count++; } strbuftemp[16]='\0'; sscanf(strbuftemp,"%lf",&d[2]); } -- ※ 發信站: 批踢踢實業坊(ptt.cc) ◆ From: 114.32.244.9

02/20 19:30, , 1F
無法理解,不過很快看到一個恐怖的,你把 %s 存到 int *
02/20 19:30, 1F

02/20 19:31, , 2F
保證 BOA
02/20 19:31, 2F

02/22 17:42, , 3F
getline一次讀一行 管他多少字元 再用strtok切空白
02/22 17:42, 3F

02/23 18:11, , 4F
排版....
02/23 18:11, 4F

02/23 18:13, , 5F
而且邏輯也怪怪的 可以附上全部的code嗎?置底有網站可以貼
02/23 18:13, 5F

02/23 21:35, , 6F
版標出現
02/23 21:35, 6F
文章代碼(AID): #1FGRl72Z (C_and_CPP)