下边的程序演示了用户输入信息,然后将信息显示到屏幕上,再将这些信息写到文件中,读者可以使用文本编辑器来查看该输出文件中的内容。
#include <iostream>
#include <fstream>
int main()
{
using namespace std;
char automobile[50];
int year;
double a_price;
double d_price;
ofstream outFile; //creat object for output
outFile.open("carinfo.txt"); //associate with a file
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;
d_price = 0.913 * a_price;
//display information on screen with cout
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 askiing $" << d_price << endl;
//now do exact same things using outFile instead of cout
outFile << fixed;
outFile.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 askiing $" << d_price << endl;
outFile.close();
return 0;
}
在运行程序之前,文件carinfo.txt文件并不存在,在这种情况下,方法open()将新建一个名为carinfo.txt的文件。如果文件存在,默认情况下,open()将丢弃原有的内容,然后将新的输出加到给文件中。