先上代码:
#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();
这样数据就能够成功读取。