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

C++ primer 第五版 中文版 练习 8.13 个人 code

2014-08-19 23:10 429 查看

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

执行结果:

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