C++读写文本文件

#include <iostream>
#include <fstream>

using namespace std;

int main()
{
const char filename[] = "mytext.txt";
ofstream o_file;
ifstream i_file;
string out_text;

//写
o_file.open(filename);
for (int i = 1; i <= 10; i++)
{
o_file << "第" << i << "行 "; //将内容写入到文本文件中
}
o_file.close();

//读
i_file.open(filename);
if (i_file.is_open())
{
while (i_file.good())
{
i_file >> out_text; //将读取的内容存储到变量out_text中
cout << out_text << endl; //在控制台输出读取的内容。为什么最后一行的内容会出现两次
}
}
else
cout << "打开文件:" << filename << " 时出错!";
i_file.close();

system("PAUSE");
return 0;
}
阅读(1044) | 评论(0) | 转发(1) |
给主人留下些什么吧!~~
评论热议
原文地址:https://www.cnblogs.com/black/p/5171795.html