c++学习笔记之简单文本输入和输出

文本输出

#include<iostream>
//(1)文本输入输出必备头文件
#include<fstream>
#include<string>

using namespace std;

void main()
{
	//(2)创建输出流对象
	ofstream ofs;
	//(3)打开输出流文件
	//第一个参数:打开文件。若文件不存在,会在c++文档同目录下创建这个文件
	//第二个参数:打开方式。都有以下几个方式:
	//ios::in 打开后读文件    ios::out 打开后写文件
	//ios::ate 打开文件跳到文件尾部 ios::app 在尾部追加写文件
	ofs.open("game.txt", ios::out);
	ofs << "蝙蝠都长这样了,还是被人吃了......" << endl;
	ofs.close();
	system("pause");
	//后面追加文字
	ofs.open("game.txt", ios::out|ios::app);
	ofs << "蝙蝠真的很无奈╮(╯▽╰)╭" << endl;
	ofs.close();
	system("pause");
	
    
    //读文件也是类似
	ifstream ifs;
	ifs.open("game.txt", ios::in);
	if (!ifs.is_open())
	{
		cout << "文件打开失败" << endl;
		return;
	}

	char buf[1024] = { 0 };
	/*while (ifs >> buf)
	{
		cout << buf;
	}*/
	/*while (ifs.getline(buf, sizeof(buf)))
	{
		cout << buf << endl;
	}*/
	//cout << endl;

	string bu;
	/*while (getline(ifs, bu))
	{
		cout << bu << endl;
	}*/
	char ch;
	while ((ch = ifs.get()) != EOF)
	{
		cout << ch;
	}
	ifs.close();
		

	system("pause");
}

运行如下:
在这里插入图片描述
继续
在这里插入图片描述在这里插入图片描述

发布了5 篇原创文章 · 获赞 5 · 访问量 138

猜你喜欢

转载自blog.csdn.net/Phil0624/article/details/104312525
今日推荐