2021-06-28

菜鸡c++笔记 文件输入输出 写入数字1-100并读取(TXT)

  1. c++ fstream
    #include
    //ofstream 写入
    //ifstream 读取
    //如果需要读写 可直接fstream包含两类。
    fstream m_file;
    m_file.open(“a.txt”); //打开文件
    m_file<<“Data”; //直接写入 类似cin
    m_file.close(); //关闭

例子:写入数字1-100并读取

#include "stdafx.h"
#include <iostream>
#include <vector>
#include <fstream>
using namespace std;


//参数是一个文件路径
//成功返回true,失败返回false
bool OutputNumber(const char* filepath)
{
	if (nullptr == filepath)
		return false;
	ofstream outfile(filepath,ios::out);
	if (!outfile)
		return false;
	for (int i = 1; i <= 100; i++)
	{
		outfile << i<<endl;
	}
	outfile.close();

	ifstream infile(filepath, ios::in);
	int a[101];
	for (int i = 0; i<100;i++)
	{
		infile >> a[i];
		cout << a[i]<<endl;
	}
	
	infile.close();
	return true;

}


int _tmain(int argc, _TCHAR* argv[])
{
	OutputNumber("D:\\data.txt");

	return 0;
}
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值