使用C++做文件處理時(shí)常用的幾個(gè)函數(shù) 查看更多見(jiàn):iii.run
文件的打開(kāi)與關(guān)閉 (open和close函數(shù))
文件讀取之前,使用open函數(shù)進(jìn)行打開(kāi)识樱。文件使用完畢后嗤无,使用close命令關(guān)閉震束。
infile.open("E:\\hello.txt");
infile.close();
文件讀取與寫(xiě)入(infile >> income,outfile << "income:")
C++中可以調(diào)用庫(kù)
#include<fstream>
之后可以使用,">>"和"<<"輸入輸出流的形式進(jìn)行文件的讀取
while (infile >> income)
{
if (income < cutoff)
tax = rate1*income;
else
tax = rate2*income;
outfile << "income:"<<left<<setw(6) << income << right<<setw(8) << "Tax:" <<tax<< endl;
}
文件夾/文件的打開(kāi)
在程序運(yùn)行完之后当犯,你可能會(huì)希望自動(dòng)將輸出的結(jié)果文件打開(kāi)垢村。調(diào) **Windows Exploler **打開(kāi)一個(gè)文件夾,
system("start E:\\tax.out");
E:\tax.out 就是你文件的地址
運(yùn)行程序demo
讀取hello.txt文件內(nèi)的收入數(shù)據(jù)嚎卫,計(jì)算稅金嘉栓,并輸出到tax.txt中
demo
hello.txt,直接 Ctrl+S 保存到E盤(pán)即可
C++代碼如下
#include<iostream>
#include<fstream>
#include<iomanip>
using namespace std;
const int cutoff = 6000;
const float rate1 = 0.3;
const float rate2 = 0.6;
void main() {
ifstream infile;
ofstream outfile;
int income, tax;
infile.open("E:\\hello.txt");
outfile.open("E:\\tax.txt");
while (infile >> income)
{
if (income < cutoff)
tax = rate1*income;
else
tax = rate2*income;
outfile << "income:"<<left<<setw(6) << income << right<<setw(8) << "Tax:" <<tax<< endl;
}
infile.close();
outfile.close();
cout << "done"<<endl;
system("start E:\\tax.txt");
}