C++實現(xiàn)將輸入的內容輸出到文本文件
更新時間:2023年08月04日 09:17:02 作者:開心的喜茶
這篇文章主要介紹了C++實現(xiàn)將輸入的內容輸出到文本文件問題,具有很好的參考價值,希望對大家有所幫助,如有錯誤或未考慮完全的地方,望不吝賜教
C++將輸入的內容輸出到文本文件
將內容輸出到文本中要用ofstream這個類來實現(xiàn)。
具體步驟如下:
ofstream mycout(“temp.txt”);//先定義一個ofstream類對象mycout,括號里面的"temp.txt"是我們用來保存輸出數(shù)據的txt文件名。這里要注意的是我們的"temp.txt"用的是相對路徑,你也可以寫絕對路徑。 mycout<<“hello”<<endl;//這樣就把"hello"輸出到temp.txt文件中了 mycout.close();//最后要記得關閉打開的文件(這里打開的就是temp.txt文件)
現(xiàn)在給你提供一個完整的程序來實現(xiàn)你說的將輸入的內容輸出到文件
#include <iostream>
#include <fstream>//ofstream類的頭文件
using namespace std;
int main()
{
int n;
cin>>n;
ofstream mycout("temp.txt");
mycout<<n<<endl;
mycout.close();
return 0;
}C++簡單文件輸入/輸出
1、寫入到文本文件
- 包含頭文件fstream
- 頭文件fstream中定義了一個用于處理輸出的ofstream類
- 需要聲明一個或多個ofstream變量(對象),
- 將ofstream對象與文件關聯(lián)起來。常用的方法是open()
- 使用完文件后,應使用方法close()將其關閉
- 可結合ofstream對象和運算符<<來輸出各種類型的數(shù)據
當創(chuàng)建好一個ofstream對象后,便可以像使用cout一樣使用它。
#include<iostream>
#include<fstream>
using namespace std;
int main()
{
char automobile[50];
int year;
double a_price;
double b_price;
ofstream outFile;
outFile.open("carimfo.txt");//打開文件,或者創(chuàng)建文件,總之就是和一個文件關聯(lián)
//默認情況下,open()將首先截斷該文件,即將其長度截短到零——丟棄原有內容,將新的輸出加入到文件。
cout << "Enter the make and model of automobile:";
cin.getline(automobile, 50);
cout << "Enter the model year:";
cin >> year;
cout << "Enter the original asking price:";
cin >> a_price;
b_price = 0.913 * a_price;
//寫入文件
outFile << "Make and model: " << automobile << endl;
outFile << "Year: " << year << endl;
outFile << "Was asking $" << a_price << endl;
outFile << "Now asking $" << b_price << endl;
outFile.close();//關閉文件
system("pause");
return 0;
}2、讀取文本文件
其操作和輸出相似
#include<iostream>
#include<fstream>
using namespace std;
int main()
{
//創(chuàng)建文件輸入對象,并打開
ifstream inFile;
inFile.open("carimfo.txt");
//判斷文件是否打開
if (!inFile.is_open())
{
cout << "Could not open the file carimfo.txt" << endl;
cout << "Program terminating.\n";
//函數(shù)exit()終止程序 EXIT_FAILURE用于同操作系統(tǒng)通信的參數(shù)值
exit(EXIT_FAILURE);
}
double value;
double sum = 0.0;
int count = 0;
while (inFile>>value)
{
//cout<<value<<endl;
count++;
sum += value;
inFile >> value;
}
if (inFile.eof())
cout << "End of file reached.\n";
else if (inFile.fail())
cout << "Input terminated by data mismatch.\n";
else
cout << "Input terminated for unknown reason.\n";
if (count == 0)
cout << "NO data processed.\n";
else{
cout << "Items read: " << count << endl;
cout << "Sum: " << sum << endl;
cout << "Average: " << sum / count << endl;
}
inFile.close();
system("pause");
return 0;
}注意:
Windows文本文件的每行都以回車字符和換行符結尾;通常情況下,C++在讀取文件時將這兩個字符轉換為換行符,并在寫入文件時執(zhí)行相反的轉換。
有些文本編輯器,不會在4自動在最后一行末尾加上換行符。
因此,如果讀者使用的是這種編輯器,請在輸入最后的文本之后按下回車鍵,再保存文件,否則最后一個數(shù)據將出現(xiàn)問題。
總結
以上為個人經驗,希望能給大家一個參考,也希望大家多多支持腳本之家。
相關文章
C++實現(xiàn)LeetCode(25.每k個一組翻轉鏈表)
這篇文章主要介紹了C++實現(xiàn)LeetCode(25.每k個一組翻轉鏈表),本篇文章通過簡要的案例,講解了該項技術的了解與使用,以下就是詳細內容,需要的朋友可以參考下2021-07-07

