C++简单文件输入/输出

73 篇文章 0 订阅
7 篇文章 0 订阅

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自动在最后一行末尾加上换行符。因此,如果读者使用的是这种编辑器,请在输入最后的文本之后按下回车键,再保存文件,否则最后一个数据将出现问题。

  • 1
    点赞
  • 15
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值