~必須包含頭文件iostream
~頭文件iostream定義了一個用處理輸出的ostream類
~頭文件iostream聲明了一個名為cout的ostream變量(對象)
~必須指明名稱空間std;例如,為引用元素cout和endl,必須使用編譯指令using或前綴std::
~可以結合使用cout和運算符<<來顯示各種類型的數據
文件輸出與此極為相似
~必須包含頭文件fstream
~頭文件fstream定義了一個用於處理輸出的ostream類
~需要聲明一個或多個ofstream變量(對象),並以自己喜歡的方式對其進行命名,條件是遵守常用的命名規則。
~必須指明名稱空間std;例如,為引用元素ofstream,必須使用編譯指令using或前綴std::。
~需要將ofstream對象與文件關聯起來。為此,方法之一是使用open()方法。
~使用完文件后,應使用方法close()將其關閉。
~可結合使用ofstream對象和運算符<<來輸出各種類型的數據。
注意,雖然頭文件iostream提供了一個預先定義好的名為cout的ostream對象,但您必須聲明自己的ofstream對象,為其命名,並將其同文件關聯起來。下面演示了如何聲明這種對象:
ofstream outfile;
ofstream fout;
下面演示了如何將這種對象與特定的文件關聯起來:
outfile.open("fish.txt");
char filename[50];
cin >> filename;
fout.open(filename);
注意,方法open()接受一個C-風格字符串作為參數,這可以是一個字面字符串,也可以是存儲在數組中的字符串。
下面演示了如何使用這種對象:
cout 控制台輸出
- 包含頭文件 iostream
- 頭文件 iostream 定義了一個 ostream 類用於處理輸出
- 頭文件 iostream 聲明了一個名為 cout 的 ostream 對象
- 指明名稱空間 std
- 可以結合使用cout和運算符<<來顯示各種類型的數據
文本文件輸出(寫入到文本文件)
- 包含文件頭 fstream
- 頭文件 fstream 定義了一個ofstream 類用於處理輸出
- 聲明一個或多個 ofstream 對象,可以自由命名
- 指明名稱空間 std
- 把 3 中聲明的 ofstream 對象與文件關聯起來,比如使用 open()方法
- 使用完文件后,需要使用 close()方法將其關閉
- 還可以結合 ofstream 對象和運算符<<來輸出各種類型的數據
注意:cout 控制台輸入輸出中,頭文件 iostream 聲明了一個名為 cout 的 ostream 對象,無需自己手動聲明;文件輸出中,我們必須自己動手聲明一個 ofstream 對象,為其命名,將其同文件關聯起來。請看下面的例子:
#include<fstream> ofstream OutFile; //聲明一個 ofstream 對象
OutFile.open("study.txt"); //將OF與“study.txt”文件關聯起來
例:
#include <iostream>
#include <fstream>
using namespace std;
int main()
{
char name[20];
double height;
double weight;
ofstream outFile;//創建了一個ofstream 對象
outFile.open("information.txt");//outFile 與一個文本文件關聯
cout << "Enter name: ";
cin.getline(automobile, 20);
cout << "Enter height: ";
cin >> year;
cout << "Enter weight: ";
cin >> weight;
// 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;
// outFile 把信息寫入到文本文件
outFile << fixed; //小數點格式顯示double
outFile.precision(2); //設置精度
outFile.setf(ios_base::showpoint); //強制顯示小數點后的零
outFile << "Name: " << name << endl;
outFile << "Height: " << height << endl;
outFile << "Weight: " << weight << endl;
outFile.close(); //使用完文本文件后要用close()方法將其關閉
return 0;
}
C++中簡單的文本文件輸入/輸出_francis_xd的博客-CSDN博客_c++文本文件輸入輸出