C++ Primer(第五版) 8.2.1--8.2.2节练习

这篇博客主要涵盖了C++ Primer第五版中8.2.1至8.2.2章节的练习内容,包括以一行文本为元素的代码实现、以单词为元素的处理、从文件读取输入记录并保存到另一个文件的技巧,以及使用输出追加模式(app)进行文件操作的示例。

8.4 代码:以一行文本为元素

#include <iostream>
#include <fstream>
#include <vector>
#include <string>

using namespace std;

int main(int argc, char *argv[])
{
	vector<string> fvec;
	string line;

	if ( argc < 2 ) {
		cout << "usage: ./file filename" << endl;
		return 0;
	}	
    //输入文件名作为argv[1]
	ifstream input(argv[1]);
	
	while ( getline(input, line) ) {
		fvec.push_back(line);
	}
	
	for ( auto l : fvec )
		cout << l << endl;
	
	return 0;
}

8.5 代码:以单词为元素

#include <iostream>
#include <fstream>
#include <vector>
#include <string>

using namespace std;

int main(int argc, char *argv[])
{
	vector<string> fvec;
	string word;
	
	if ( argc < 2 ) {
		cout << "usage: ./file2 filename" << endl;
		return 0;
	}	
	ifstream input(argv[1]);
	
	while ( input >> word ) {
		fvec.push_back(word);
	}
	
	for ( auto l : fvec )
		cout << l << endl;
	
	return 0;
}

8.6--8.7 代码:从一个文件读取输入记录,将结果保存到另一个文件

#include <iostream>
#include <fstream>
#include "Sales_data.h"

using namespace std;

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 {
				print(output, total) << endl;
				total = trans;
			}
			print(output, total) << endl;
		}
	} else {
		cerr << "No data?!" << endl;
	}
	
	return 0;
}

 

8.8 代码:输出追加模式(app)

#include <iostream>
#include <fstream>
#include "Sales_data.h"

using namespace std;

int main(int argc, char *argv[])
{	
	ifstream input(argv[1]);
	ofstream output;
	//模式为输出追加
	output.open(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 {
				print(output, total) << endl;
				total = trans;
			}
			print(output, total) << endl;
		}
	} else {
		cerr << "No data?!" << endl;
	}
	
	output.close();

	return 0;
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值