【C++ Primer Plus习题】17.7
国中之林 2024-10-02 11:35:04 阅读 68
问题:
解答:
#include <vector>
#include <string>
#include <fstream>
#include <algorithm>
using namespace std;
const int LIMIT = 50;
void ShowStr(const string& str);
void GetStrs(ifstream& fin, vector<string>& v);
class Store
{
private:
string str;
ofstream* fout;
public:
Store(ofstream&out):fout(&out){ }
bool operator()(const string& str);
~Store(){ }
};
void ShowStr(const string& str)
{
cout << str << endl;
}
void GetStrs(ifstream& fin, vector<string>& v)
{
unsigned int len;
char* p;
while (fin.read((char*)&len, sizeof len))
{
p = new char[len];
fin.read(p,len);
v.push_back(p);
}
}
bool Store::operator()(const string& str)
{
unsigned int len = str.length();
if (fout->is_open())
{
fout->write((char*)&len, sizeof len);
fout->write(str.data(), len);
return true;
}
else
{
return false;
}
}
int main()
{
vector<string> vostr;
string temp;
cout << "Enter strings (empty line to quit):\n";
while (getline(cin, temp) && temp[0] != '\0')
vostr.push_back(temp);
cout << "Here is your input.\n";
for_each(vostr.begin(), vostr.end(),ShowStr);
ofstream fout("strings.txt", ios_base::in | ios_base::binary);
for_each(vostr.begin(), vostr.end(), Store(fout));
fout.close();
vector<string>vistr;
ifstream fin("strings.txt", ios_base::in | ios_base::binary);
if (!fin.is_open())
{
cerr << "Could not open the file for input.\n";
exit(EXIT_FAILURE);
}
GetStrs(fin, vistr);
cout << "\nHere are the strings read from the file:\n";
for_each(vistr.begin(), vistr.end(), ShowStr);
return 0;
}
拜了个拜!
声明
本文内容仅代表作者观点,或转载于其他网站,本站不以此文作为商业用途
如有涉及侵权,请联系本站进行删除
转载本站原创文章,请注明来源及作者。