【C++】将文件中的内容显示到屏幕上

将文本文件以及二进制文件从文件中读取并显示到屏幕上

【文本文件输出】

文本文件一般以行读读数据

#include<iostream>
#include<fstream>
#include<string>
using namespace std;
int main()
{
	ofstream fin("e:\\chen.tex");
	if(!fin)
	{
		cout<<"打开文件错误!"<<endl;
		return 0;
	}
	fin<<"飞机"<<endl;
	fin<<"中国"<<endl;
	ifstream fout("e:\\chen.tex");
	if(!fout)
	{
		cout<<"打开文件失败!"<<endl;
		return 0;
	}
    string bu;
	while(getline(fout,bu))//将文件中数据一行一行读取出存在bu中
	{
		cout<<bu<<endl;
	}
	fin.close();
	fout.close();
	system("pause");
	return 0;
}

(1)第一种就是上面代码的方法,定义一个string类型来接收文件数据,并输出

(2)定义一个char类型,然后用数组表示

(3)定义一个string类型

 【二进制文件输出】

以数据类型的方式组织数据

#include<iostream>
#include<fstream>
#include<string>
using namespace std;
class AA
{
private:
	string name;
	float score;
public:
	void inputname()//相当于赋初值,可以省略构造函数
	{
		cin >> name;
	}
	void inputscore()
	{
		cin >> score;
	}
	string getname()
	{
		return name;
	}
	float getscore()
	{
		return score;
	}
};
int main()
{
	AA C[100];
	string ch;
	int k=0;//用来记录输入的次数,用以后面输出时的暂停
	ofstream outfile("e:\\chen.dat", ios::binary );
	if (!outfile)
	{
		cout << "无法打开文件" << endl;
	}
	for (int i = 0;i<100; i++)
	{
		cout << "请输入科目:";
		C[i].inputname();
		cout << "请输入成绩:";
		C[i].inputscore();
		outfile.write((char*)&C[i], sizeof(AA));
		cout << "是否继续输入(y/n)";
		cin >> ch;
		if (ch == "n" || ch == "N")
		{
			k = i;
			break;
		}
	}
	outfile.close();
	AA A2[100];
	ifstream infile("e:\\chen.dat", ios::binary );
	if (!infile)
	{
		cout << "无法打开文件" << endl;
	}
	for (int j = 0; j< 100; j++)
	{
		infile.read((char*)&A2[j], sizeof(AA));
		cout << "编号:" << j + 1 << endl;
		cout << "学科:" << A2[j].getname() << endl;
		cout << "成绩:" << A2[j].getscore() << endl;
		if (j == k)
			break;
	}
	infile.close();
	system("pause");
	return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值