Z01 fstream中ofstream的简单用法

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()将首先截断该文件,即长度截短到零(丢失原有内容),然后将新的输出加入到该文件中。但是可以修改这种方式,会在后续介绍。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值