C++基础读写

C++ 简单的txt文件读取

本人初学C++ 如有遗漏和错误,望斧正!
本文只是简单的介绍一下C++对txt文件的简单读和写
希望大家喜欢
给个赞就最好了
(。・∀・)ノ

1. C++ txt 文件 写

1.1演示

#include<iostream>
#include<fstream> // 读写专用文件

int main()
{
	using namespace std;

	ofstream outFile; // 建立一个名为outFile的对象
	outFile.open("filename.txt"); //建立连接文件及所写文件
	int a; // 建立int a
	cin >> a; // 输入 a 的值
	outFile << a << endl; // 输入出a的值到outFilew所连接的文件中
	outFile.close(); // 关闭文件

	system("pause");
	return 0;
}

1.2注意事项

outFile.open("filename.txt"); // 如果open的是一个已存在的txt文件那么,open()就会截断文件及---丢失原有的内容

2.C++ txt 文件 读

2.1测试文档

测试文档名为“filename.txt”内容为

123
234
345

2.2演示

#include<iostream>
#include<fstream> // 读写专用库
#include<cstdlib> // exit() 函数 用于 跳出 程序

int main()
{
	using namespace std;

	ifstream inFile; // 建立名为inFile的对象
	inFile.open("filename.txt");// 连接要读取数据的文档

	if (!inFile.is_open()) // 检查 文档是否打开 否则跳出
	{
		cout << "Dead!" << endl;
		exit(EXIT_FAILURE);
	}

	int Ret[10] = {0};
	int count = 0;
///
	while (inFile.good()) // 当文件 是 正差输出 并且没有 遇到 EOF 时
	{
		inFile >> Ret[count]; // 存入
		count++;
	}
    有更优秀的写法↓

    
	if (inFile.eof())
	{
		for(int i=0;i<count-1;i++)
		{
			cout << Ret[i] << endl; // 倒序输出
		}
	}
	else if (inFile.fail())
		cout << "INPUT mismatch" << endl; // 文件打开失败
	else
		cout << "dead for unknown reason" << endl; // 未知原因
	if (count == 0)
	{
		cout << "without data" << endl;//没有读到数字
	}
	else
	{
		cout << "DONE!" << endl;//结束
	}
    inFile.close(); // 关闭文件
	system("pause");
	return 0;
}

2.3 精简 写法

	while (inFile >> Ret[count])
	{
		count++;
        //循环
	}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值