powerwind 发表于 2005-12-11 18:15

C++写一个简单的电话簿

先介绍点东西.
原型:extern char *strtok(char *s, char *delim);

功能:分解字符串为一组标记串。s为要分解的字符串,delim为分隔符字符串。

说明:首次调用时,s必须指向要分解的字符串,随后调用要把s设成NULL。
      strtok在s中查找包含在delim中的字符并用NULL('\0')来替换,
      直到找遍整个字符串。返回指向下一个标记串。
      当没有标记串时则返回空字符NULL。

字符串string类有一个方法char* c_str().

假设有文件a.txt
张三010-87589542
李四020-87589693
王五030-96325896

#include<iostream>
#include<fstream>
#include<string>
using namespace std;

const char *filename="a.txt";
const int LEN=256;
void find();
void append();

int main()
{
    int i=0;
    while(1==1){
      cout<<"1,查询\n2,添加记录\n3,退出\n";
      cin>>i;
      if(i==1)find();
      else if(i==2)append();
      else if(i==3)return 0;
      else cout<<"Error input!"<<endl;
    }
}

void find()
{
    char tmp;
    char name;
    char* temp;
    bool Foundflag=false;
    cout<<"请输入你要查询的名字:"<<endl;
    cin>>name;
    fstream in(filename,ios::in);
    if(!in){cout<<"Cann't open the file: "<<filename<<endl;exit(1);}
    while (in.getline(tmp,LEN)){
          temp=strtok(tmp," ");
      if (strcmp(tmp,name)==0)
         {
         Foundflag=true;
         while (temp!=NULL){cout<<temp<<" ";temp=strtok(NULL," ");}
         cout<<endl;
         //break;如果不注释掉,则允许有重复名字
         }
          }
    in.close();
    if(!Foundflag)cout<<"没有找到:"<<name<<endl;
}

void append()
{
   
    fstream out(filename,ios::out|ios::app);
    cout<<"请输入记录集--->(以#结束)"<<endl;
    cout<<"姓名 电话号码"<<endl;
    string s;
    getline(cin,s,'#');
    const char *p=s.c_str();
    out.write(p,s.size());
    out.close();
   
}

用程序诠释生命 发表于 2005-12-11 18:44

真的简单到没什么好说的了。

wool王 发表于 2005-12-11 21:47

支持原创,顶一下。

hjack 发表于 2005-12-12 16:29

用户名: hjack [退出登录]
作者: powerwind
评分: 积分 12 点
标题: C++写一个简单的电话簿

盼望 发表于 2005-12-31 10:54

阅!!!!!!!!!
页: [1]
查看完整版本: C++写一个简单的电话簿