Re: [問題] 簡單的字串搜尋程式

看板C_and_CPP (C/C++)作者 (software everywhere)時間16年前 (2009/08/08 03:14), 編輯推噓1(100)
留言1則, 1人參與, 最新討論串2/3 (看更多)
※ 引述《a5170040 (Piggy)》之銘言: : 目的:讓使用者輸入ID : 讀取進來資料的第一列為我們的ID,第二列開始才是data : 藉由我們所輸入的ID讓程式能搜尋到這是在檔案的哪一行 : (就是變數在第幾行的意思) : 以利後續做資料分析 : 我目前只能做到如果資料全部都是數值,我可以順利做資料分析 ^^^^ 架構出來 應該就是換 operation吧 #include <cstdio> #include <cstdlib> #include <cstring> using namespace std; static FILE *l_file=0; typedef struct{ unsigned long ID; char *pch_name; }StudentInfo; static StudentInfo l_IdName[100]={0}; //max has 100 students // load data from file to mem. void read_file(){ int idxRow=0; l_file = fopen("sample.txt","r"); if( l_file == 0) return; while( !feof(l_file) ){ unsigned long ID=0; char tmp_name[100]={0};//temp string to hold the student name char *p_name = 0; fscanf(l_file, "%d%*c%s", &ID, tmp_name); l_IdName[idxRow].ID = ID; // duplicate the name p_name = (char*)malloc( strlen(tmp_name)+1 ); strcpy( p_name, tmp_name ); l_IdName[idxRow].pch_name = p_name; //如果兩個都是 string的話 就用string的方式 //把 ID的 assign動作代換掉 idxRow++; } } //search id:name data at mem. const char* getName_byID(const unsigned long ID_){ unsigned int idxRow=0; for( idxRow=0;l_IdName[idxRow].pch_name!=0 ;idxRow++){//linear search. if(ID_ == l_IdName[idxRow].ID) return l_IdName[idxRow].pch_name; //如果是string 把相等性判斷 換成 strcmp(X,Y) == 0 } return 0; } int main(){ read_file(); unsigned long ID1,ID2; const char *p_name1,*p_name2; printf("請選擇班對 :\n"); printf("學號 1:\n"); scanf("%d",&ID1); printf("學號 2:\n"); scanf("%d",&ID2); p_name1 = getName_byID(ID1); p_name2 = getName_byID(ID2); printf("%s 和 %s 在一起! 在一起! 在一起!\n", p_name1,p_name2 ); system("pause"); return 0; } 資料檔案 "sample.txt" 範例如下 ----------- file start -------------- 1 nick 2 jack 3 jeff 4 jackson 5 smith 6 smithson 7 andy 8 anderson 9 bill 10 Bob 11 gate 12 hero 13 keoi ----------- file end ----------------- -- ※ 發信站: 批踢踢實業坊(ptt.cc) ◆ From: 118.166.112.99

08/08 11:47, , 1F
謝謝你....我試試看!謝謝
08/08 11:47, 1F
文章代碼(AID): #1AV7qDOX (C_and_CPP)
討論串 (同標題文章)
文章代碼(AID): #1AV7qDOX (C_and_CPP)