重点语句,均在代码中指出:
ofstream outFile; // outFile 可使用cout可使用的任何方法。
outFile.open(“carinfo.txt”);
cout << fixed;
cout.precision(2);
outFile.setf(ios_base::showpoint);
#include <iostream>
#include <fstream> // 该头文件定义了一个用于输出的ofstream类
using namespace std;
int main()
{
char automobile[50];
int year;
double a_price;
double b_price;
// 声明一个或多个ofstream对象,并以自己细化的方式对其进行命名,条件时遵守常用的命名规则。
ofstream outFile; // create object for output, outFile 可使用cout可使用的任何方法。
// 若carinfo.txt 存在,默认丢弃其原有内容,重新接受输入。若不存在,则创建。
outFile.open("carinfo.txt"); // associate with a file
cout << "Enter the make and model of automobile:";
cin.getline(automobile, 50); // 最多录入49个字符外加1个空字符。
cout << "Enter the model year:";
cin >> year;
cout << "Enter the original asking price:";
cin >> a_price;
b_price = 0.913 * a_price;
//display information on screen with cout
// 用一般的方式输出浮点型,例如C++程序在控制台显示的时候大一点的数,显示的时候使用了科学计数法,使用该命令即可像一般的方式显示
cout << fixed; // 加了fixed意味着是固定点方式显示,所以下面的的精度变为了小数的位数
cout.precision(2); // 设置精确度为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;
//now do exact same thing using outFile instead of cout
outFile << fixed; // 加了fixed意味着是固定点方式显示,所以下面的的精度变为了小数的位数
outFile.precision(2); // 设置精确度为2,并返回上一次的设置
outFile.setf(ios_base::showpoint); // 显示浮点数小数点后面的零。
outFile << "Make and model: " << automobile << endl;
outFile << "Year: " << year << endl;
outFile << "Was asking $" << a_price << endl;
outFile << "Now asking $" << b_price << endl;
outFile.close(); // done with file
return 0;
}
输出结果:
文件内容: