作者softwind (software everywhere)
看板C_and_CPP
标题Re: [问题] 简单的字串搜寻程式
时间Sat Aug 8 03:14:11 2009
※ 引述《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
1F:推 a5170040:谢谢你....我试试看!谢谢 08/08 11:47