//outfile.cpp--writing a file
#include<iostream>
#include<fstream>
int main()
{
using namespace std;
char automobile[50];
int year;
double a_price;
double d_price;
ofstream outFile;
outFile.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;
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 asking $" << d_price << endl;
//now do exact same things using outFile instead of cout
outFile << fixed;
outFile.precision(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 $" << d_price << endl;
outFile.close();
return 0;
}
输出:
Enter the make and model of automobile:Flitz Perky
Enter the model year:2009
Enter the original asking price:13500
make and model :Flitz Perky
Year:2009
Was asking $13500.00
Now asking $12325.50
查看文件所在位置,看到一个名为carinfo.txt的新文件.