C++文件读写常用操作
作者:互联网
C++文件读写常用操作
最近的毕设工作要使用C++保存读取一些矩阵,此篇博文记录比较好用的C++文件读写操作。
写
#include <iostream>
#include <fstream>
#include <sstream>
#include <string>
using namespace std;
int main()
{
float mat[3][3] = {{1,2,3}, {4,5,6}, {7,8,9}};
string pic = "./output/mat.txt";
// transfer string to char*
char* pic_name = (char*)pic.data();
ofstream fout;
fout.open(pic_name);
for (int i = 0; i < 3; ++i)
for (int j = 0; j < 3; ++j)
fout << mat[i][j] << " ";
fout.close();
return 0;
}
读
#include <iostream>
#include <fstream>
#include <sstream>
#include <string>
using namespace std;
int main()
{
string path = "./output/mat.txt";
char* pic_name = (char*)path.data();
fstream in(pic_name);
string line;
while (getline(in, line))
{
double value;
stringstream ss(line);
// 按行读取
while (ss >> value)
{
cout << value << endl;
}
}
in.close();
return 0;
}
标签:常用,string,int,读写,pic,C++,char,include 来源: https://www.cnblogs.com/programmerwang/p/16134509.html