c++入門之輸出文件流ofstream


 1 # include "iostream"
 2 # include"fstream"
 3 int main()
 4 {
 5     using namespace std;
 6 
 7     char automobile[50];
 8     int year;
 9     double a_price;
10     double d_price;
11 
12     ofstream outfile;
13     outfile.open("C:/Users/kb409/Desktop/carinfo.txt");//注意,這里使用"/"而不是"\"
14     //outfile.open("carinfo.txt");
15     cout << "Enter the make and model of automobile:";
16     cin.getline(automobile, 50);
17     cout << "Enter the model year:";
18     cin >> year;
19     cout << "Enter the original asking price:";
20     cin >> a_price;
21     d_price = 0.913*a_price;
22 
23     cout << fixed;//cout<<fixed是以一般格式而不是科學計數法輸出浮點數
24     cout.precision(4);//控制輸出流顯示浮點數的數字個數
25     cout.setf(ios_base::showpoint);//顯示最后一位小數后面的0;
26     cout << "Make and model:" << automobile << endl;
27     cout << "Year:" << year << endl;
28     cout << "Was asking 's" << a_price << endl;
29     cout << "Now asking 's" << d_price << endl;
30     ////////////////////////////////
31     outfile << fixed;//fixed未被定義,那么這里fix是什么?
32     outfile.precision(2);
33     outfile.setf(ios_base::showpoint);
34     outfile << "Make and model:" << automobile << endl;
35     outfile << "Year:" << year << endl;
36     outfile << "Was asking 's" << a_price << endl;
37     outfile << "Now asking 's" << d_price << endl;
38     outfile.close();
39     system("pause");
40     return 0; 
41 }

該段代碼的功能是:通過cout輸出字符到顯示端,同樣的通過ofstream對象輸出字符到文件端.。關於端輸出流ostream和文件輸出流fstream的一些本質性描述如下:

上述<<c++ prime plus>>中描述了控制台輸出和文件輸出的基本流程。從其中可以看出,控制台輸出和文件輸出本質上差別並不大,只是對象不同而已,.

針對上面給出的代碼,總結要點:

1 第13行代碼outfile.open("C:/Users/kb409/Desktop/carinfo.txt");//注意,這里使用"/"而不是"\"  ,雖然桌面文件采用的“\”,但很明顯c++支持的是"/",否則無法生成文件

2 關於23到25的代碼,只是對數據格式的一個處理,見如下:

(給出該知識點博客地址:https://blog.csdn.net/septemberAs/article/details/68489554)

以上屬於知識點型,不需要記憶,但要注意總結的第一條.

以及需要認識到的是.控制台輸出和文件輸出至少從這里看是遵循相同的規則的


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM