第八章 8.2.1节练习

题目:

练习 8.4:

编写函数,以读模式打开一个文件,将其内容读到一个string的vector中,将每一行作为一个独立的元素存于vector中。


练习 8.5:

重写上面的程序,将每个单词作为一个独立的元素进行存储。


练习8.6:

重写7.1.1节的书店程序(第229页),从一个文件中读取交易记录。将文件名作为一个参数传递给main(参见6.2.5节,第196页)


个人解答:

8.4和8.5属于一道题,当然只要你比较认真的学习了这节的内容,那这道题几乎没什么难度。

8.6题,其实在284页中已经解答了,这里我就把书上的代码粘出来。

#include <iostream>
#include <fstream>

#include <string>
#include <vector>

using namespace std;

#define DEBUG

void one_line(const char *str){
	// for 8.4
	vector<string> line_buf;
	string temp;
	ifstream in(str);

	if (!in.good()){
		cout << "The file not exist!! Please check your enter." << endl;
		exit(-1);
	}

	while (getline(in, temp)){
		line_buf.push_back(temp);
		if (!in.good()){
			break;
		}
	}
	in.close();
#ifdef DEBUG
	for (auto i : line_buf){
		cout << i << "\n";
	}
#endif
}

void single_char(const char *str){
	// for 8.5
	vector<char> char_buf;
	ifstream in(str);

	if (!in.good()){
		cout << "The file not exist!! Please check your enter." << endl;
		exit(-1);
	}

	while (in.good())          // loop while extraction from file is possible
	{
		char_buf.push_back(in.get());       // get character from file
		if (!in.good()){
			break;
		}
	}

	in.close();                // close file
#ifdef DEBUG
	for (auto i : char_buf){
		cout << i << "\n";
	}
#endif
}

int main() {
	char str[256];
	string a;

	std::cout << "Enter the name of an existing text file: ";
	std::cin.get(str, 256);    // get c-string 

	one_line(str); // for 8.4
	single_char(str);  // for 8.4
	return 0;
}

//... for 8.6

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())	// 检查isbn
		total.combine(trans);			// 更新销售总额
	else{
		print(output, total) << endl;	// 打印结果
		total = trans;					// 处理下一本书
	}
  }
  print(output, total) << endl;			// 打印最后一本书的销售额
}	
else{									// 文件中无输入数据
  cerr << "No data?!" << endl;
}

//...


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值