C++ primer 第五版 中文版 练习 8.13
题目:重写本节的电话号码程序,从一个命名文件而非cin读取数据。
答:
#include <iostream>
#include <fstream>
#include <sstream>
#include <string>
#include <vector>
using std::vector;
using std::string;
using std::ifstream;
using std::ofstream;
using std::istringstream;
using std::ostringstream;
using std::endl;
struct PersonInfo{
string name;
vector<string> phones;
};
int main(int argc,char **argv)
{
ifstream finput(argv[1]);
ofstream foutput(argv[2],std::ofstream::app);
string line, word;
vector<PersonInfo> people;
while (getline(finput, line))
{
PersonInfo info;
istringstream record(line);
record >> info.name;
while (record >> word)
info.phones.push_back(word);
people.push_back(info);
}
for (const auto &a : people)
{
ostringstream ostr;
for (const auto &b : a.phones)
{
ostr <<" "<< b;
}
foutput << a.name << " " << ostr.str() << endl;
}
return 0;
}
输入文件:1.txt
morgan 2015552368 8625550123
drew 9735550130
lee 6095550123 2015550175 8005550000
输出文件:2.txt
执行结果: