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

C++primer(第五版)8.2.2节练习答案

2015-02-11 14:01 309 查看
练习8.7:修改上一节的书店程序,将结果保存到一个文件中。将输出文件名作为第二个参数传递给main函数。

解答:

#include<iostream>
#include<fstream>

#include<../ch07/ex7_26.h>

using std::ofstream;using std::endl;using std::ifstream;using std::cerr;

int main(int argc,char **argv)
{
ifstream input(argv[1]);
ofstream output(argv[2]);

Sales_data total;
if(read(input,total))
{
Sales_data trans;
while(read(input,trans))
{
if(total.isbn() == trans.isbn())
total.combine(trans);
else
{
printf(output,total)<<endl;
total = trans;
}
}
printf(output,total)<<endl;
}
else
{
cerr<<"No data?!"<<endl;
}

return 0;
}


练习8.8:修改上一题的程序,将结果追加到给定的文件末尾。对同一个输出文件,运行程序至少两次,检验数据是否得以保留。

解答:

#include<iostream>
#include<fstream>

#include<../ch07/ex7_26.h>

using std::ofstream;using std::endl;using std::ifstream;using std::cerr;

int main(int argc,char **argv)
{
ifstream input(argv[1]);
ofstream output(argv[2],ofstream::app);

Sales_data total;
if(read(input,total))
{
Sales_data trans;
while(read(input,trans))
{
if(total.isbn() == trans.isbn())
total.combine(trans);
else
{
printf(output,total)<<endl;
total = trans;
}
}
printf(output,total)<<endl;
}
else
{
cerr<<"No data?!"<<endl;
}

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