C++文本資料寫入,文本資料寫入

來源:互聯網
上載者:User

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了。所以在開啟檔案的時候,進行檔案是否開啟正常的判斷非常重要。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.