您的位置:首页 > 编程语言 > C语言/C++

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

2014-05-02 13:06 609 查看
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);//看api
return 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);//看api

return 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;
else
return 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

————————————————————————————————————————————————————————————————————————————
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息