1、首先了解学习一下C++中的iostream头文件与fstream头文件。
iostream中包括istream与ostream,其相对应cin与cout。
fstream中包括ifstream与ofstream,其相对应inFile与outFile。
2、用法及功能
cin与inFile的用法是一样的,cout与outFile也是一样的。
其中cout是将输入的内容显示到屏幕上,而outFile是将cout显示到屏幕上的内容写入到文件中。
3、文件写入的主要步骤
(1)包含头文件fstream。
(2)创建一个ofstream对象。
(3)将该ofstream对象同一个文件关联起来。
(4)像使用cout那样使用该ofstream对象。
程序例子:
#include <iostream>
#include <fstream>
using namespace std;
int main()
{
char automobile[50];
int year;
double a_price;
double b_price;
ofstream outFile;
outFile.open("corinfo.txr");
cout << "Enter the make and modle of automobile: ";
cin.getline(automobile,50);
co