#-----------------写入到文本文件中----------------#
/*
01)包含头文件fstream
02)创建一个ofstream对象,名字可以任意取
03)将该ofstream对象和一个文件关联起来,方法之一就是用open()方法
04)就可以像使用cout一样去使用该ofstream对象了
05)必须知名名称空间std,例如,为引用元素ofstream,必须使用编译指令using或前缀std::
06)使用完文件后,应使用方法close()将其关闭
*/

 1 #include <iostream>
 2 #include <fstream>  //for file I/O  01) 包含头文件
 3 
 4 int main()
 5 {
 6     using namespace std;
 7 
 8     char automobile[50];
 9     int year;
10     double a_price;
11     double b_price;
12 
13     ofstream outFile;  // 02) 创建一个ofstream对象
14     outFile.open("carinfo.txt");  //03) 将该ofstream对象(outFile)和一个文件关联起来,
15                                  //此后就可以像使用cout一样使用outFlie
16     cout << "Enter the make and model of automobile:";
17     cin.getline(automobile, 50);
18     cout << "Enter the model year: ";
19     cin >> year;
20     cout << "Enter the original asking price: ";
21     cin >> a_price;
22     b_price = 0.913 * a_price;
23 
24     //display infomation on screen with cout
25     cout << fixed;  //使用一般方式输出浮点数,而不是可科学计数法
26     cout.precision(2);  //设置2为浮点数的精度值
27     cout.setf(ios_base::showpoint);  //显示小数点后面的0
28     cout << "Make the model: " << automobile << endl;
29     cout << "Year: " << year << endl;
30     cout << "was asking $" << a_price << endl;
31     cout << "Now asking $" << b_price << endl;
32 
33     //Now do exact same things using outFile instead of cout
34     //但是outFile将cout在屏幕上显示的内容写入到了carinfo.txt文件中
35     //如果原来没有carinfo.txt文件,那么会自动创建
36     //该代码将文件创建在了和main.cpp在同一个文件夹中,但是在编译环境中没有显示出该文件
37     //如果已存在该文件,那么会默认情况下会覆盖掉文件中所有的内容
38     outFile << fixed;  //使用一般方式输出浮点数,而不是可科学计数法
39     outFile.precision(2);  //设置2为浮点数的精度值
40     outFile.setf(ios_base::showpoint);  //显示小数点后面的0
41     outFile << "Making and model: " << automobile << endl;
42     outFile << "Year: " << year << endl;
43     outFile << "was asking $" << a_price << endl;
44     outFile << "Now asking $" << b_price << endl;
45     outFile.close(); //关闭文本文件
46 
47     system("pause");
48 
49     return 0;
50 }
写文件

相关文章: