一、將數據寫入文件
void writeToFile()
{
std::ofstream outfile;
outfile.open("data.txt"); //創建、打開文件
for(unsigned int x = 0; x < N; x++)
{
for(unsigned int y = 0; y < M; y++)
{
outfile<<data[x * N + y]<<" "; //寫入數據
}
outfile<<std::endl;
}
outfile.close(); //關閉文件
}
二、從文件中讀取數據
void readFormFile()
{
fstream in;
in.open("data.txt"); //打開文件
//逐字符讀取
char c;
while(!in.eof())
{
in>>c;//讀取字符
//其他操作
}
//逐行讀取
string str;
while(getline(in,str))
{
//其他操作
}
in.close();//關閉文件
}
ps:
頭文件#include <fstream>