C++用ofstream先写入文件再用ifstream读取文件,数据读取失败

先上代码:

#include<string>
#include<iostream>
#include<fstream>
using namespace std;

int main() {
	string sarr[] = {"this","study","unable","to","open","the","necessary","the","end","unable","this","open"};
	int str_size = sizeof(sarr) / sizeof(string);
	ofstream outfile("D:\\VisualStusioProject\\test.txt");
	ifstream infile("D:\\VisualStusioProject\\test.txt");
	if (!outfile || !infile) {
		cout << "文件打开失败" << endl;
		return -1;
	}
	//通过iterator_iostream将字符串写入到文本中
	ostream_iterator<string> os(outfile, " ");
	copy(sarr, sarr + str_size, os);
	
	//读取并输出文件内容
	string name;
	while (infile >> name) {
		cout << name << " ";
	}
}

此时输出的结果为空:
在这里插入图片描述
但文本已经成功写入到txt文档中了
在这里插入图片描述
错误的原因在于,在对文件进行读取前,并没有将之前写入创建的对象关闭,导致读取失败,因此需要在读取前加入close()函数关闭写入的文件对象。

outfile.close();

这样数据就能够成功读取。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值