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

看板C_and_CPP (C/C++)作者 (Piggy)時間16年前 (2009/08/07 18:50), 編輯推噓0(000)
留言0則, 0人參與, 最新討論串1/3 (看更多)
目的:讓使用者輸入ID 讀取進來資料的第一列為我們的ID,第二列開始才是data 藉由我們所輸入的ID讓程式能搜尋到這是在檔案的哪一行 (就是變數在第幾行的意思) 以利後續做資料分析 我目前只能做到如果資料全部都是數值,我可以順利做資料分析 但是只要變數名稱換成英文或中文,就搜尋不到了 (也就是說可以讓使用者輸入英文,藉由這個字串搜尋變數在第幾行) 以下是我用全部數值的結果跑出來的程式碼 #include <cstdio> #include <cmath> #include <iostream> #include <fstream> #include <cstring> using namespace std; double **data; char **name1;//變數名稱 int ncol=0,nrow=0; int y,x; FILE *in; void file_in(void){ int i,j; char word,word2; ifstream ifile("D:\\pairs.txt",ios::in); while(!ifile.eof()){ ifile.get(word); if(word == '\n') nrow++; } ifile.close(); ifstream ifile1("D:\\pairs.txt",ios::in); while(word2!='\n'){ ifile1.get(word2); if(word2 == '\t') ncol++; } ifile1.close(); nrow=nrow+1; ncol=ncol+1; ifstream ifile2("D:\\pairs.txt",ios::in); //-------------------印出data------------------------ data=(double**)malloc(nrow*sizeof(*data)); for(int i=0;i<nrow;i++)*(data+i)=(double*)malloc((ncol+1)*sizeof(double)); for(i=0;i<nrow;i++) for(j=0;j<ncol;j++) ifile2>>data[i][j]; ifile2.close(); //----------------------印出這筆資料 ----------------------- /* for(i=0;i<nrow;i++){ for(j=0;j<ncol;j++) printf("%8.0f\t",data[i][j]); printf("\n"); } cout<<" 列="<<nrow<<endl; cout<<" 行="<<ncol<<endl; */ /* 讀文字檔案 */ name1=(char**)malloc(ncol*sizeof(*name1)); for(int i=0;i<ncol;i++) *(name1+i)=(char*)malloc((20+1)*sizeof(char)); in=fopen("D:\\pairs.txt","r"); for(i=0;i<nrow;i++){ if(i==0){ for(j=0;j<ncol;j++){ fscanf(in,"%s",name1[j]);//讀近來每個變數選項總共有ncol個 //printf("%s\t",name1[j]); } } }fclose(in); } int main(void) { file_in(); int Indep,depen; cout<<" 請選擇班對 : "<<endl; cout<<" 學號 1 : ";cin>>Indep; cout<<" 學號 2 : ";cin>>depen; int j=0; while(data[0][j]!=Indep){ j=j+1; } y=j-1; cout<<" 學號 "<<Indep<<"在第"<<y<<"行"<<endl; j=0; while(data[0][j]!=depen){ j=j+1; } x=j-1; cout<<" 學號 "<<Indep<<"在第"<<x<<"行"<<endl; cout<<" 在一起!在一起!在一起!"<<endl; system("pause"); return 0; } 輸入中文或英文可以找到對應的行 麻煩各位好心人士幫忙一下了 謝謝!!!!! -- -- -- ※ 發信站: 批踢踢實業坊(ptt.cc) ◆ From: 59.104.118.85 ※ 編輯: a5170040 來自: 59.104.118.85 (08/07 18:50) ※ 編輯: a5170040 來自: 59.104.118.85 (08/07 18:51)
文章代碼(AID): #1AV0RSf- (C_and_CPP)
文章代碼(AID): #1AV0RSf- (C_and_CPP)