C ++ Text Data Writing and Text Data Writing
To write text data to a program in C ++, you must first understand the specific process of the entire process.
1. Add the required header file: # include <fstream>.
2. Define the corresponding variables to store the data written to the file.
3. Create an ofstream object.
4. Associate ofstream with text files.
5. Use ofstream object and <operator to write data.
6. Disable the function after the ofstream object is used.
Code example:
#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;}
After the program is running, a text file info.txt will be generated in the target folder. If this file does not exist in the folder before, and the data in the text is the same as the data output on the console.
However, if the info.txt file exists in the target folder before the program is migrated, all data in the original text will be cleared and the text length will be truncated to zero by default.
There is also a possibility that opening an existing file may fail because it has no permission or the file is damaged. In this case, the program is basically over. Therefore, when opening a file, it is very important to judge whether the file is opened normally.