C++primer plus第六版课后编程题答案17.7

来源:互联网 发布:手机画板软件哪个好 编辑:程序博客网 时间:2024/06/11 12:30

main177.cpp

#include <iostream>#include <fstream>#include <vector>#include <iterator>#include <string>#include <algorithm>//for for_each()//#define end "\n"//简单测试一下而已using namespace std;static void ShowStr(const string &s){cout<<s<<endl;};static bool store(ofstream &fout,string &s){if(fout.good()){int len=s.length();fout.write((char*)&len,sizeof(size_t));fout.write(s.data(),len);//看apireturn true;}return false;}/*用类我无法实现这个功能,谁实现了麻烦告诉我下class Store{private://ifstream fin;//接受的应该是ifstream对象//fstream fst;public:ofstream fout;//Store(){};Store(ofstream &os):fout(os){};//构造函数//Store(const Store &s)bool operator()(const string &s){int len=s.length();//fout.write((char*)&len,sizeof(size_t));//fout.write(s.data(),len);//看apireturn true;}};*/static bool GetStrs(ifstream &fin,vector<string> &str){int len;//while(!fin.eof()&&fin.good())while(fin.read((char*)&len,sizeof(size_t)))//用这个作为判断的时候才能正确执行,//难道fin有特殊的?{//string t;//int len;//fin.read((char*)&len,sizeof(size_t));//cout<<len<<endl;string t="";//t的值每次都要更新while(len--){char ch;ch=fin.get();t=t+ch;}str.push_back(t);}if(fin.eof())return true;elsereturn false;};void main177(){vector<string> vostr;string temp;cout<<"Enter string (q to quit):"<<endl;while(getline(cin,temp)&&temp!="q") {vostr.push_back(temp);}cout<<"Her is your input:"<<endl;for_each(vostr.begin(),vostr.end(),ShowStr);ofstream fout("str.dat",ios_base::out|ios_base::binary|ios_base::app);//ofstream fout("strings.dat",ios_base::out|ios_base::binary);//是|而不是||//for_each(vostr.begin(),vostr.end(),Store(fout));//由Strore(fout)可知Strore应该是一个类//Store的具体实现不太会,对于函数符中如何传递的原理不太懂vector<string>::iterator it=vostr.begin();for(;it!=vostr.end();++it){store(fout,*it);//用这个实现}fout.close();vector<string> vistr;ifstream fin("str.dat",ios_base::in|ios_base::binary);if(!fin.is_open()){cerr<<"Could not open file for input."<<endl;exit(EXIT_FAILURE);}GetStrs(fin,vistr);cout<<endl<<"Here are the strings read fronm the file:"<<endl;for_each(vistr.begin(),vistr.end(),ShowStr);fin.close();cin.get();}


------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------

下面是一个网友的改进,感谢分享!

class Store{
private:
    std::ofstream &os;
public:
    Store(std::ofstream &os_) : os(os_){}
    void operator()(const std::string & str){
        int n = str.length();
        os.write((char *)&n, sizeof(int));
        os.write(str.c_str(), str.length());
    }
};

---2014.9.16

————————————————————————————————————————————————————————————————————————————


0 0