C++文本資料寫入,文本資料寫入
在C++中進行文本的資料寫入程式中,首先需要瞭解整個流程的具體過程。
1.添加必須的標頭檔:#include <fstream>。
2.定義相應的變數,用於隱藏檔寫入的資料。
3.建立一個ofstream對象。
4.將ofstream與文字檔進行關聯。
5.使用ofstream對象和<<運算子進行資料寫入。
6.使用完ofstream對象後關閉。
代碼執行個體:
#include <iostream>#include <fstream>int main(){using namespace std;char arr[50];int year;double price;ofstream outFile;// create object for outputoutFile.open("info.txt");// associate with a filecout << "Enter the published place of the book: ";cin.getline(arr,50);cout << "Enter the model year: ";cin >> year;cout << "Enter the original asking price: ";cin >> price;// display information on screen with coutcout << fixed;cout.precision(2);cout.setf(ios_base::showpoint);cout << "Place: " << arr << endl;cout << "Year: " << year << endl;cout << "Price:" << price << endl;// now do exact same things using outFile instead of cout outFile << fixed;outFile.precision(2);outFile.setf(ios_base::showpoint);outFile << "Place: " << automobile << endl;outFile << "Year: " << year << endl;outFile << "Price: " << a_price << endl;outFile.close(); // done with filereturn 0;} 上述程式運行之後,會在目標檔案夾中產生一個info.txt的文字檔,如果之前此檔案夾中沒有存在這個檔案的話,並且文本中的資料和控制台輸出的資料相同。
但是,如果在程式運行之前,目標檔案夾中就存在info.txt這個檔案,則原先文本中的所有資料將被清除,將文本長度預設截斷為零。
還存在一種可能性就是,開啟已存在的檔案失敗,原因可能是沒有許可權或者是檔案已損壞等等。這樣的話,這個程式基本就over了。所以在開啟檔案的時候,進行檔案是否開啟正常的判斷非常重要。