1、引言
本篇内容简单介绍ofstream(output file stream)的用法,ofstream是从内存到硬盘,本例即将数据写入到文本中。
2、比较iostream与fstream
1)用iostream的准备
- 必须包含头文件iostream;
- 头文件iostream定义了一个用于处理输出的ostream类;
- 头文件iostream声明了一个名为cout的ostream变量对象;
- 必须指明名称空间std;
- 可以结合cout和运算符<<来显示各种类型的数据。
2)用fstream的准备
- 必须包含头文件fstream;
- 头文件fstream定义了一个用于处理输出的ofstream类;
- 需要声明一个或多个ofstream变量对象;
- 必须指明名称空间std;
- 需要将ofstream对象与文件关联起来,方法之一是open();
- 使用完成后,应使用方法close()将其关闭;
- 可以结合ofstream与运算符<<来输出各种类型的数据。
3、示例代码
#include <iostream>
#include <fstream>
int main(void)
{
using namespace std;
char automobile[50];
int year;
double a_price, b_price;
ofstream fout;
fout.open("..\\carinfo.txt");
cout << "Enter the make and model of automobile: ";
cin.getline(automobile, 50);
cout << "Enter the model year: ";
cin >> year;
cout << "Enter the original asking price: ";
cin >> a_price;
b_price = a_price * 0.913;
//显示信息
cout << fixed;
cout.precision(2);
cout.setf(ios_base::showpoint);
cout << "Make and model: " << automobile << endl;
cout << "Year: " << year << endl;
cout << "Was asking $" << a_price << endl;
cout << "Now asking $" << b_price << endl;
//使用fout代替cout
fout << fixed;
fout.precision(2);
fout.setf(ios_base::showpoint);
fout << "Make and model: " << automobile << endl;
fout << "Year: " << year << endl;
fout << "Was asking $" << a_price << endl;
fout << "Now asking $" << b_price << endl;
fout.close();
system("pause");
return 0;
}
a、控制台输出
b、文本输出
注意点:程序运行之前,文件carinfo.txt并不存在,方法open()将新建一个文件。如果运行程序前,文件carinfo.txt已经存在,默认情况下,open()将首先截断该文件,即长度截短到零(丢失原有内容),然后将新的输出加入到该文件中。但是可以修改这种方式,会在后续介绍。