在日常工作中,我们会遇到大量的数据读取和写入操作。这其中就包括读取文本数据。用文本存储数据的好处是简单、通用(即不管是在Windows下还是在Liux下,它都能被正常读写)。下面是一个很简单的C++程序,通过这个小程序,我们将看到如何使用C++文件流(fstream)简便、快捷的读写文本数据。
/*
这个程序要实现的是读取位于程序目录下的data.txt文件中的数据,然后将它写入同一目录下的test.txt文件中。
data.txt文件的格式(不包括——————)
————————
0 20
20 60
40 80
60 100
80 120
100 140
120 100
140 59.9
160 60
180 90
200 120
220 150
240 180
————————*/
#include <iostream>
#include <fstream> //to use ifstream, the head file "fstream" shoulded be stated here
using namespace std;
int main()
{
ifstream openfile;
ofstream savefile("./test.txt",ios::app);
double tc[200]={0};
double t[200]={0};
int i=0;
openfile.open("./data.txt",ios::in);
while(!openfile.eof())
{
openfile>>tc[i]; //read the first colum data to tc[]
openfile>>t[i]; //read the second colum data to t[]
savefile< i++;
}
openfile.close();
savefile.close();
}
回复Comments
作者:
{commentrecontent}