#include<iostream>
#include<cstdlib>
#include<cstdio>
#include<cstring>
#include<cctype>
#include<string>
#include<fstream>
using namespace std;
class entry
{
private:
string name;
string phone;
public:
void keyin();
string getname()
{
return name;
}
string getphone()
{
return phone;
}
void addone(fstream &file)
{
cin.get();
cout<<"請輸入新鍵項目的姓名 :";
getline(cin,name);
cout<<"請輸入新鍵項目的電話號碼 :";
getline(cin,phone);
//newone.keyin();
file.seekp(0,ios_base::end);
file<<name<<','<<phone<<endl;;
cout<<"已存檔!\n";
}
c++字串結束符為'\0',文件结束符為0xFF.C++ 读到文件结束符0xFF時,file.eof()=1且file.tellg()=-1,而文件结束符是最后一个字符的下一个字符。必須使用file.clear()重置為0,才能將游標返回之前的上一個位置.
在執行lookup函式時,當找到人員的電話,立即執行return返回,故不會執行到尾端以使file.eof()=1(就算執行到尾端,file.eof()僅會在
下一次迴圈時才為1),此時重置file.eof()=0的file.clear()可省略不執行.
lookup(fstream &file)函式內所執行的file.seekg(0,ios_base::beg) ,在file.eof()=1(此時輸出file.tellg()=-1)的狀態下,無法將游標返回起始位置,故若產生file.eof()=1,則必須使用file.clear()重置為0.才能將游標返回之前的上一個位置,再利用file.seekg(0,ios_base::beg)才能使游標返回起始位置.
void lookup(fstream &file)
{
cout<<"要找誰的電話 :";
string name;
cin.get();
getline(cin,name);
entry who;
file.seekg(0,ios_base::beg);
while(!file.eof())
{
getline(file,who.name,',');
getline(file,who.phone,'\n');
//file>>who;
if(name==who.name)
{
cout<<"電話號碼是 "<<who.phone<<endl;
//return;
}
}
cout<<"沒有這個人的資料"<<endl;
cout<<"file.eof() = "<<file.eof() <<endl;
cout<<"file.tellg() = "<<file.tellg()<<endl<<endl;
file.clear();
cout<<"file.eof() = "<<file.eof() <<endl;
cout<<"file.tellg() = "<<file.tellg()<<endl<<endl;
}
};
void entry::keyin()
{
cin.get();
cout<<"請輸入新鍵項目的姓名 :";
getline(cin,name);
cout<<"請輸入新鍵項目的電話號碼 :";
getline(cin,phone);
}
int main()
{
entry work;
fstream file("telbook.txt",ios_base::in|ios_base::out);
if(!file)
cerr<<"open file fail"<<endl;
else
{
int choice;
do
{
cout<<"請選擇功能: 1.輸入資料 ,2.搜尋資料 ,3.結束程式 ";
cin>>choice;
if(choice==1)
work.addone(file);
else if(choice==2)
work.lookup(file);
else if(choice>3)
cout<<" input number wrong, input 1 or 2 or 3 , try again"<<endl;
}while(choice!=3);
cout<<"....goodbye....";
}
}
留言列表