c++ txt文件读取与写入

#include <fstream>

using std::istringstream;
using std::ifstream;
using std::ofstream;
using std::ostringstream;

头文件fstream,四个类型。

istringstream:字符串流类型

ifstream:读入文件内的字符串流

ofstream:打开一个文件,默认是截取,即文件的旧数据被丢弃。

                因此可以用ofstream::app,app(append)追加、添加。

ostringstream:输出流,可以用<<不断向其添加字符串。

#include "mylib7.h"
#include <fstream>

using std::istringstream;
using std::ifstream;
using std::ofstream;
using std::ostringstream;

int main() {
	string file1 = "s.txt";//filename
	string file2 = "s2.txt";
	ifstream input(file1);//input is the file1's contents
	ofstream out;//out is a file will be writen
	ostringstream ofile;//ofile is a stream to store strings
	string line;
	string word;
	vector<string> vst;
	string::size_type cnt=0;
	while (getline(input, line)) {//take a line from stream input to line
		vst.push_back(line);
		++cnt;
		
		istringstream record(line);//make the record to store line's content
		while (record >> word) {
		
			cout << word<<' ';
			ofile << word << ' ';//add string to ostream ofile
		}
		cout << endl;
		ofile << endl;
		
	}
	for (int i = 0; i < cnt; ++i) {
	
		istringstream record(vst[i]);
		while (record >> word) {

			cout << word << ' ';
		}
		cout << endl;
	}
	out.open(file2, ofstream::app);//open file2 by append
	out << ofile.str();
	out.close();

		
		


}

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

糖豆人鄭

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值