在编写数值分析作业QR分解过程中,用到将数据结果写入文件的操作,在c++中用流来实现:
#include<iostream>
#include<fstream>//用到ofstream类时要用
//主函数中
ofstream file_Qr;
file_Qr.open("output_Qr.txt", ios::out);
for (int i = 0; i < N; i++)
{
for (int j = 0; j < N; j++)
{
if (abs(Qr[i][j]) < E)Qr[i][j] = 0;
file_Qr << setiosflags(ios::scientific) << setprecision(12) << setw(20) << Qr[i][j];// << endl;
//cout << A[i][j] << " " << endl;
// printf("%f ", A[i][j]);
}
//cout << '\n' << endl;
file_Qr<< "\n" << endl;
//printf("\n");
}
在c++中头文件fstream定义了三个类:
ifstream:从文件读取
ofstream:写入文件
fstream:读写文件
初始化方式:fstream fstrm(string file_name)或fstrm.open(string file_name);
这三种类型与其他IO类型不同的操作(以fstream为例):fstream.open(file_name);fstream.close();fstream.is_open();
在primer c++ 中,第八章讲解IO库类型,IO库类型包括:
iostream:cin即为istream类的一个对象,cout为ostream类的一个对象
fstream:如上
sstream:istringstream,ostringstream读写内存string对象