1、写入到文本文件
1、包含头文件fstream
2、头文件fstream中定义了一个用于处理输出的ofstream类
3、需要声明一个或多个ofstream变量(对象),
4、将ofstream对象与文件关联起来。常用的方法是open()
5、使用完文件后,应使用方法close()将其关闭
6、可结合ofstream对象和运算符<<来输出各种类型的数据
当创建好一个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");//打开文件,或者创建文件,总之就是和一个文件关联
//默认情况下,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()
{
//创建文件输入对象,并打开
ifstream inFile;
inFile.open("carimfo.txt");
//判断文件是否打开
if (!inFile.is_open())
{
cout << "Could not open the file carimfo.txt" << endl;
cout << "Program terminating.\n";
//函数exit()终止程序 EXIT_FAILURE用于同操作系统通信的参数值
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++在读取文件时将这两个字符转换为换行符,并在写入文件时执行相反的转换。 有些文本编辑器,不会在4自动在最后一行末尾加上换行符。因此,如果读者使用的是这种编辑器,请在输入最后的文本之后按下回车键,再保存文件,否则最后一个数据将出现问题。