最近的毕设工作要使用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; }