C++文本文件操作|写入和读取

C++txt文件读取和写入 write.open("E:\\practice\\程序设计B\\ttt.txt",ios::in);read.open("E:\\practice\\程序设计B\\ttt.txt",ios::out);cout << "输入id,name,grade" << endl;cout << "文件打开失败!" << endl;write << "学生管理" << endl; 阅读详情

前言

C++中,文件操作属于技术的应用,不是基本语法
程序运行的时候数据存储在内存中
程序没有运行的时候
数据持久化的两种方式:文件和数据库
在实际开发中,文件操作无处不在

文件操作属于IO
IO类继承关系
![[Pasted image 20240518084053.png]]

写入文本文件

文本文件一般以行的形式组织数据
包含头文件#include <fstream>
类ofstream

新建文件写入
#include <iostream>
#include <fstream>
using namespace std;

int main()
{
	ofstream fout; //创建文件输出流对象

	fout.open("test.txt"); //打开文件,如果文件不存在,则创建它;如果文件已存在,则截断其内容

	//向文件中写入数据
	fout << "xxx" << endl;
	fout << "yyy" << endl;
	fout << "zzz" << endl;

	fout.close(); //关闭文件,fout对象失效前会自动调用close()

	cout << "文件操作完成" << endl;
}

![[Pasted image 20240518085131.png]]

程序在哪个目录运行,生成的文件就在哪个目录
![[Pasted image 20240518085213.png]]

![[Pasted image 20240518085225.png]]

open()成员函数的参数,可以用c风格的字符串,也可以用string
open()函数有重载,两种参数都支持

#include <iostream>
#include <fstream>
using namespace std;

string filename = "test.txt";
//char filename[] = "test.txt";

int main()
{
	ofstream fout; //创建文件输出流对象

	fout.open(filename); //打开文件,如果文件不存在,则创建它;如果文件已存在,则截断其内容

	//向文件中写入数据
	fout << "xxx" << endl;
	fout << "yyy" << endl;
	fout << "zzz" << endl;

	fout.close(); //关闭文件,fout对象失效前会自动调用close()

	cout << "文件操作完成" << endl;
}
指定文件写入

在实际开发中,一般会把数据文件夹存放在指定目录
所以filename要用文件的全路径,不能只是文件名

#include <iostream>
#include <fstream>
using namespace std;

string filename = "D:\\data\\txt\\test.txt";
//char filename[] = "test.txt";

int main()
{
	ofstream fout; //创建文件输出流对象

	fout.open(filename); //打开文件,如果文件不存在,则创建它;如果文件已存在,则截断其内容

	//向文件中写入数据
	fout << "xxx" << endl;
	fout << "yyy" << endl;
	fout << "zzz" << endl;

	fout.close(); //关闭文件,fout对象失效前会自动调用close()

	cout << "文件操作完成" << endl;
}

C++中\用于转义,可以用\\

其他写法

R"(D:\data\txt\test.txt) //原始字面量
"D:/data/txt/test.txt"   //用反斜杠
"/data/txt/test.txt"     //Linux中

打开文件,可以用open()成员函数
也可以在ofstream fout的时候,传入文件名

ofstream fout(filename);

ofstream类有重载的构造函数,在函数中会打开文件

#include <iostream>
#include <fstream>
using namespace std;

string filename = "D:\\data\\txt\\test.txt";
//char filename[] = "test.txt";

int main()
{
	ofstream fout(filename); //创建文件输出流对象

	//fout.open(filename); //打开文件,如果文件不存在,则创建它;如果文件已存在,则截断其内容

	//向文件中写入数据
	fout << "xxx" << endl;
	fout << "yyy" << endl;
	fout << "zzz" << endl;

	fout.close(); //关闭文件,fout对象失效前会自动调用close()

	cout << "文件操作完成" << endl;
}
打开模式

打开模式
如果文件已经存在,打开模式可以决定是否清空原文件内容

ios::out     缺省值,会截断文件内容
ios::trunc   截断文件内容
ios::app     不截断文件内容,只在文件末尾追加文件

这三行代码效果一样

ofstream fout(filename);
ofstream fout(filename, ios::out);
ofstream fout(filename, ios::trunc);

用open函数和构造函数是一样的

判断打开文件是否成功

判断打开文件是否成功

if (fout.is_open() == false)
{
	cout << "打开文件" << filename << "失败" << endl;
	return 0;
}

失败的原因主要有

  1. 目录不存在
  2. 磁盘空间已满
  3. 没有权限,Linux中常见

读取文本文件

#include <iostream>
#include <fstream>
using namespace std;

string filename = "D:\\data\\txt\\test.txt";
//char filename[] = "test.txt";

int main()
{
	ifstream fin; //创建文件输出流对象
	fin.open (filename, ios::in);

	if (fin.is_open() == false)
	{
		cout << "打开文件" << filename << "失败" << endl;
		return 0;
	}
	
	//读取文件内容
	
	fin.close(); //关闭文件,fin对象失效前会自动调用close()

	cout << "文件操作完成" << endl;
}

输入流只有一种打开模式

ios::in

缺省值,这个参数填不填都一样

ifstream fin(filename);
ifstream fin(filename, ios::in);

读取文件内容代码
文本文件一般以行的方式组织数据
所以读取数据的时候要一行一行地读
从输入流中读取一行数据,可以用getline()函数
需要包含string头文件

string buffer;
getline(fin, buffer);

从文件中读取一行数据,存放在buffer中

读取文件全部内容

如果想要读取文件中全部数据,要用一个while循环

方法一
while (getline(fin, buffer))
{
	cout << buffer << endl;
}

把文件的内容一行一行读出来,放到buffer中
如果文件结束了,getline会返回空

#include <iostream>
#include <fstream>
#include <string>
using namespace std;

string filename = "test.txt";
//char filename[] = "test.txt";

int main()
{
	ifstream fin; //创建文件输出流对象
	fin.open (filename, ios::in);

	if (fin.is_open() == false)
	{
		cout << "打开文件" << filename << "失败" << endl;
		return 0;
	}
	
	//读取文件内容
	string buffer;
	while (getline(fin, buffer))
	{
		cout << buffer << endl;
	}

	fin.close(); //关闭文件,fin对象失效前会自动调用close()

	cout << "文件操作完成" << endl;
}

![[Pasted image 20240518093840.png]]

方法二
char buffer[101];  //存放从文件中读取的内容
//如果采用ifstream.getline(),一定要保证缓冲区足够大
while (fin.getline(buffer, 100))
{
	cout << buffer << endl;
}

getline()是输入流ifstream的成员函数,不是全局函数
参数也不同,第二个参数是最多读取内容的字节数
buffer是c风格的字符串,不能扩展,要保证足够大

方法三
string buffer;
while (fin >> buffer)
{
	cout << buffer << endl;
}

会间隔空格和换行符读取

C++ 高级教程:C++ 文件和流 到目前为止,我们已经使用了iostream标准库,它提供了cin和cout方法分别用于从标准输入读取流和向标准输出写入流。 本教程介绍如何从文件读取流和向文件写入流。这就需要用到 C++ 中另一个标准库fstream,它定义了三个新的数据类型: C/C++的学习裙【七一二二八四七零五】,无论你是小白还是进阶者,是想转行还是想入行都可以来了解一起进步一起学习!裙内有开发工具,很多干货和技术资料分享! 打开文件 在从文件读取信息或者向文件写入信息之前,必须先打开文件。ofstre... 阅读详情

相关推荐

C++之文件的读取和写入操作(文本文件和二进制文件)

1.声明 当前内容主要为本人学习和记录C++的文件写入和读取操作 主要包括 使用ifstream读取文件内容 使用ofstream向文件中写入内容 2.写入demo /* * FileWriteTxtTest.cpp * * Created on: 2021年5月3日 * Author: hy * 当前内容主要为测试和使用C++来向abc.txt文件中写入数据操作 */ #include<iostream> #include<fstream> #inclu

编程学习者的博客 9697

C/C++文件读写(最全方法,多种实现)

主要讲解C/C++处理文件的多种实现方法

余识- 14万+

C++ 利用 ifstream 和 ofstream 读取和修改文件内容

C 语言读取文件的时候很麻烦,C++ 相对来说有很方便的库可以用,方便的多,所以平常开发中推荐使用 C++ 中的库去读写文件。本文介绍如何利用 C++ 进行最简单的读写文件操作。 fstream 库 用到的关键库是 fstream. 在教科书上最常见的输出输入库是 iostream 但是它针对的是标准的输入输出设备读写,而 fstream 是针对文件的。 它有 3 个很重要的类。 ifstrea...

frank 的专栏 1万+

C/C++将内容写入文件的方法总结。

最近总在做文件读入和写出的事,索性来总结一下C/C++将内容写入文件的方法吧。本篇氛围C和C++两种方式,C的方法有些单调,毕竟没有库函数。C++则丰富些,下面我把搜集到的整理一下,供大家参考。 一、C语言输出内容到文件 二、C++文件输入/输出流 三、文件输入/输出流迭代器 四、C++ 中的文件输入/输出流缓冲区 五、C++ 中的文件输入/输出流预定义的操纵符 六、windows api

Bobowen的博客 1万+

C++中文件的读取和写入操作

输入输出相关类 C++中输入出的类的关系如图所示: 其中对文件的操作相关类为ifstream和ofstream,依赖于头文件#include <fstream>,具体来说对文件的操作是通过指针来操作的,对输入文件,有一个读指针;对输出文件,有一个写指针;对输入输出文件,有输入输出指针,可以通过seekp()或seekg()函数来改变指针指向的位置,从而读取或写入文件的不同位置,比如对...

基于msg的ROS话题发布 1024

C++如何进行文本文件的读写操作

上述代码首先创建了一个ifstream对象file,并使用open()函数打开了一个名为"example.txt"的文件。然后,使用std::getline()函数逐行读取文件内容并存储在字符串line中。上述代码首先创建了一个ofstream对象file,并使用open()函数打开了一个名为"example.txt"的文件。可以使用endl来实现换行。在C++中,可以通过使用标准库中的fstream头文件来进行文本文件的读写操作。下面将详细介绍如何使用C++读写txt文件,并给出相应的源代码和描述。

TechProX的博客 461

对文本文件读取和写入操作C++实现

读取txt文件 读取一个TXT文件中的每一行到一个向量中,代码如下 bool readTxtfile(string strPath, vector<vector<float>>& TxtData) { ifstream txtfile(strPath); if (!txtfile.is_open()) return 0; string str; while (getline(txtfile, str)) { istringstream input(str);

qq_36559293的博客 3046

c++读取写入txt文件

读取写入txt文件,一个小小的程序,用c++读取txt文件

C++文件操作——文本文件和二进制文件的读取写入

学习b站黑马程序员匠心之作笔记

m0_46254725的博客 913

eNSP无法启动AR报错码40,而且按照eNSP帮助手册排查都没用,我的处理方法【自己存档版】

eNSP无法启动AR报错码40,而且按照eNSP帮助手册排查都没用,我的处理方法【自己存档版】

mizhiakk的博客 8408

【效率手册】Kylin-Desktop-V10-SP1 麒麟系统核心组件实战——从入门到精通的6个关键场景

本文针对Kylin-Desktop-V10-SP1麒麟系统用户,通过文件管理、系统监视、设置优化等6个核心场景实战,深度解析如何高效运用系统内置工具解决文件混乱、性能卡顿、外设驱动等实际问题,帮助用户从功能认知跃升至场景化应用,真正释放国产操作系统的生产力潜能。

weixin_29208327的博客 119

C++之文本文件的读取和写入

博客1:C++文本文件的读取和写入 博客2:C++创建txt文件并读写 博客3:C++文件流在ios类中定义 博客4:C++文件操作详解(ifstream、ofstream、fstream) 使用文件流对象打开文件后,文件就成为一个输入流或输出流。对于文本文件,可以使用 cin、cout 读写。 在《C++文件类(文件流类)》一节中提到,流的成员函数和流操纵算子同样适用于文件流,因为 ifstre...

杨杨子江的博客 1906

OpenNARS开源通用人工智能系统:非公理推理引擎实践指南

人工智能系统从基于规则推理到深度学习模型,始终围绕如何让机器具备智能决策能力。传统逻辑系统依赖公理和完备知识,而现实世界智能体需要在资源受限、信息不完备环境下进行推理。非公理推理系统(NARS)通过动态真值计算和信念修正机制,实现了在不确定性环境下的自主学习和决策。这种推理引擎的技术价值在于模拟人类思维的核心机制——归纳、演绎和学习,为通用人工智能(AGI)提供了不同于数据驱动的新路径。在应用场景上,NARS适用于游戏NPC决策、复杂系统故障诊断和自适应机器人控制等领域。OpenNARS作为NARS理论的开

weixin_31961675的博客 408

C++ 文件操作

访问方式使用。

Jacker优快云的博客 959

CAPL实战:从零构建HEX文件解析器,赋能UDS刷写

本文详细介绍了如何使用CAPL从零构建HEX文件解析器,以支持UDS刷写操作。通过解析HEX文件格式、设计状态机、优化数据结构与算法,实现高效准确的固件数据处理,并提供了与UDS刷写流程对接的工程化实践建议。

weixin_28726391的博客 443

在 Windows 上安装 OpenCV – C++ / Python

而且,安装并不是一件容易的事。这些安装程序仅适用于安装 OpenCV for C++。如果您想安装适用于 Python 的 OpenCV,您将在博客后面找到相关信息。在这篇博文中,我们将在 Windows 上安装适用于 C++ 和 Python 的 OpenCV。C++ 安装是在自定义安装 exe 文件的帮助下完成的。而Python的安装是通过Anaconda完成的。从源代码安装 OpenCV 需要花费大量时间。根据您的硬件和安装配置,该过程可能需要 5 分钟到 2 小时不等。

Demondai999的博客 2091

C++非文本文件写入混乱

C++文件读写问题 C++使用fstream读取非文本文件时,一般常规读取就可以,例如将图片读取出来并存储到std::string ifstream File_test1; File_test1.open("tt1.jpg", std::ios::in); std::string str; File_test1>>str; 但是写入时就会有些坑,非文本类文件需要以二进制写入,例如 ofstream File_test2("tt2.jpg", std::ios::binary | std::i

windSnowLi 1万+

brpc组件bvar源码解析(一)简介、使用和类的关系

bvar是brpc中的一个重要组件,brpc内部有很多builtin监控都是bvar实现的。 brpc文档介绍bvar“几乎不会给程序增加性能开销,也快于竞争频繁的原子操作”。它的原理是:多线程累加一个计数器时,每个线程只累加私有的变量而不参与全局竞争,因此写时没有锁的竞争;在读取时累加所有线程的私有变量。虽然读比之前慢多了,但写就快多了,因此它使用写多读少的场景,例如统计、监控场景。 1.使用 // bvar::Adder<T>用于累加,下面定义了一个统计read error总数的Adder。

华秋实的专栏 1851

C++文件读写操作(二)逐字符读取文本和逐行读取文本

相关文章 C++文件读写操作(一)将字母表写入TXT文本文件  C++文件读写操作(二)逐字符读取文本和逐行读取文本  C++文件读写操作(三)如何统计文本的行数及如何读取文件某一行内容  C++文件读写操作(四)读取文件数据到临时数组   #include #include using namespace std; void testBy

聚精会神搞建设 7万+

OpenClaw Manager Pro - 可视化管理工具

OpenClaw Manager Pro 是一个现代化的 Web 管理界面,用于管理多个 OpenClaw Gateway 实例。🎨美观的界面:深色主题,渐变设计,现代化 UI📡实时监控:WebSocket 实时推送状态和日志🔧完整管理:创建、编辑、删除、启动、停止 Gateway📊多渠道支持:飞书、Telegram、Discord、Slack、微信、钉钉🧩技能管理:可视化配置 61+ 个技能🌍跨平台:支持 macOS、Linux、Windows使用自定义模型系统会自动在中创建},

Maynor的博客 3086

05、CAN 总线拓扑结构详解,线型拓扑搭建要点

CAN总线拓扑与信号完整性优化 本文通过工程实践经验,深入剖析了CAN总线系统中信号完整性的关键要素。主要内容包括: 终端电阻的核心作用:必须严格在总线两端配置120Ω电阻,形成60Ω等效阻抗以匹配双绞线特性阻抗,避免信号反射导致的波形畸变。 阻抗匹配原理:解释了信号能量管理机制,指出阻抗不连续会导致信号反射,并通过示波器波形特征(如振铃现象)判断阻抗失配问题。 信号完整性多维要求:强调信号质量不仅涉及波形存在与否,还包括边沿斜率、共模电压范围等关键参数,这些直接影响通信可靠性。 工程实践建议:提供了终端电

2401_88858637的博客 178

C++文件操作(1)

C++文件操作 1.文本的写入及读取 文本文件写入 文本文件读取 2.二进制文件的写入及读取 二进制文件写入 二进制文件读取 3.小结

weixin_54929649的博客 1322

Devexpress16.2.6破解工具

Devexpress16.2.6破解工具Devexpress16.2.6破解工具Devexpress16.2.6破解工具Devexpress16.2.6破解工具

C++ 学习(15)文件操作、文件文件读与写操作、二进制文件读与写操作

本章主要学习C++文件操作 - 文件文件读(4种操作)与写操作、二进制文件读与写操作,针对这些操作,使用Go语言也实现了一下

ling1998的博客 1461

汉书HE8,好用的汇编代码编写工具

汉书HE8,好用的汇编代码编写工具早期编写汇编代码所用功能强大

STM32F407中文手册

STM32f407中文手册 本参考手册面向应用开发人员,提供有关使用 STM32F405xx/07xx、STM32F415xx/17xx、 STM32F42xxx 和 STM32F43xxx 微控制器存储器与外设的完整信息。STM32F405xx/07xx、STM32F415xx/17xx、STM32F42xxx 和 STM32F43xxx 构成一个微 控制器系列,各产品具有不同的存储器大小、封装和外设。有关订购信息以及器件的机械与电气特性,请参见数据手册。有关 ARM Cortex™-M4F 内核的信息,请参见《Cortex™-M4F 技术参考手册》。

利用C++写入和读取文件

在网上看了很多,发现写入文件内容的比较多 一、利用C++来写入文件 #include <iostream> #include <fstream> using namespace std; int main() { freopen("123.txt", "r", stdin);//打开文件 freopen("123.txt", "w", stdout)...

Littlehero_121的博客 1038

深度学习工具包 DeepLearningToolbox

深度学习工具包Deprecation notice.-----This toolbox is outdated and no longer maintained.There are much better tools available for deep learning than this toolbox, e.g. [Theano](http://deeplearning.net/software/theano/), [torch](http://torch.ch/) or [tensorflow](http://www.tensorflow.org/)I would suggest you use one of the tools mentioned above rather than use this toolbox.Best, Rasmus.DeepLearnToolbox================A Matlab toolbox for Deep Learning.Deep Learning is a new subfield of machine learning that focuses on learning deep hierarchical models of data.It is inspired by the human brain's apparent deep (layered, hierarchical) architecture.A good overview of the theory of Deep Learning theory is[Learning Deep Architectures for AI](http://www.iro.umontreal.ca/~bengioy/papers/ftml_book.pdf)For a more informal introduction, see the following videos by Geoffrey Hinton and Andrew Ng.* [The Next Generation of Neural Networks](http://www.youtube.com/watch?v=AyzOUbkUf3M) (Hinton, 2007)* [Recent Developments in Deep Learning](http://www.youtube.com/watch?v=VdIURAu1-aU) (Hinton, 2010)* [Unsupervised Feature Learning and Deep Learning](http://www.youtube.com/watch?v=ZmNOAtZIgIk) (Ng, 2011)If you use this toolbox in your research please cite [Prediction as a candidate for learning deep hierarchical models of data](http://www2.imm.dtu.dk/pubdb/views/publication_details.php?id=6284)```@MASTERSTHESIS\{IMM2012-06284, author = "R. B. Palm", title = "Prediction as a candidate for learning deep hierarchical models of data", year = "2012",}```Contact: rasmusbergpalm at gmail dot comDirectories included in the toolbox-----------------------------------`NN/` - A library for Feedforward Backpropagation Neural Networks`CNN/` - A library for Convolutional Neural Networks`DBN/` - A library for Deep Belief Networks`SAE/` - A library for Stacked Auto-Encoders`CAE/` - A library for Convolutional Auto-Encoders`util/` - Utility functions used by the libraries`data/` - Data used by the examples`tests/` - unit tests to verify toolbox is workingFor references on each library check REFS.mdSetup-----1. Download.2. addpath(genpath('DeepLearnToolbox'));Example: Deep Belief Network---------------------```matlabfunction test_example_DBNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit RBM and visualize its weightsrand('state',0)dbn.sizes = [100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);figure; visualize(dbn.rbm{1}.W'); % Visualize the RBM weights%% ex2 train a 100-100 hidden unit DBN and use its weights to initialize a NNrand('state',0)%train dbndbn.sizes = [100 100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);%unfold dbn to nnnn = dbnunfoldtonn(dbn, 10);nn.activation_function = 'sigm';%train nnopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.10, 'Too big error');```Example: Stacked Auto-Encoders---------------------```matlabfunction test_example_SAEload mnist_uint8;train_x = double(train_x)/255;test_x = double(test_x)/255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit SDAE and use it to initialize a FFNN% Setup and train a stacked denoising autoencoder (SDAE)rand('state',0)sae = saesetup([784 100]);sae.ae{1}.activation_function = 'sigm';sae.ae{1}.learningRate = 1;sae.ae{1}.inputZeroMaskedFraction = 0.5;opts.numepochs = 1;opts.batchsize = 100;sae = saetrain(sae, train_x, opts);visualize(sae.ae{1}.W{1}(:,2:end)')% Use the SDAE to initialize a FFNNnn = nnsetup([784 100 10]);nn.activation_function = 'sigm';nn.learningRate = 1;nn.W{1} = sae.ae{1}.W{1};% Train the FFNNopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.16, 'Too big error');```Example: Convolutional Neural Nets---------------------```matlabfunction test_example_CNNload mnist_uint8;train_x = double(reshape(train_x',28,28,60000))/255;test_x = double(reshape(test_x',28,28,10000))/255;train_y = double(train_y');test_y = double(test_y');%% ex1 Train a 6c-2s-12c-2s Convolutional neural network %will run 1 epoch in about 200 second and get around 11% error. %With 100 epochs you'll get around 1.2% errorrand('state',0)cnn.layers = { struct('type', 'i') %input layer struct('type', 'c', 'outputmaps', 6, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %sub sampling layer struct('type', 'c', 'outputmaps', 12, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %subsampling layer};cnn = cnnsetup(cnn, train_x, train_y);opts.alpha = 1;opts.batchsize = 50;opts.numepochs = 1;cnn = cnntrain(cnn, train_x, train_y, opts);[er, bad] = cnntest(cnn, test_x, test_y);%plot mean squared errorfigure; plot(cnn.rL);assert(er<0.12, 'Too big error');```Example: Neural Networks---------------------```matlabfunction test_example_NNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);% normalize[train_x, mu, sigma] = zscore(train_x);test_x = normalize(test_x, mu, sigma);%% ex1 vanilla neural netrand('state',0)nn = nnsetup([784 100 10]);opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samples[nn, L] = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.08, 'Too big error');%% ex2 neural net with L2 weight decayrand('state',0)nn = nnsetup([784 100 10]);nn.weightPenaltyL2 = 1e-4; % L2 weight decayopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex3 neural net with dropoutrand('state',0)nn = nnsetup([784 100 10]);nn.dropoutFraction = 0.5; % Dropout fraction opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex4 neural net with sigmoid activation functionrand('state',0)nn = nnsetup([784 100 10]);nn.activation_function = 'sigm'; % Sigmoid activation functionnn.learningRate = 1; % Sigm require a lower learning rateopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex5 plotting functionalityrand('state',0)nn = nnsetup([784 20 10]);opts.numepochs = 5; % Number of full sweeps through datann.output = 'softmax'; % use softmax outputopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex6 neural net with sigmoid activation and plotting of validation and training error% split training data into training and validation datavx = train_x(1:10000,:);tx = train_x(10001:end,:);vy = train_y(1:10000,:);ty = train_y(10001:end,:);rand('state',0)nn = nnsetup([784 20 10]); nn.output = 'softmax'; % use softmax outputopts.numepochs = 5; % Number of full sweeps through dataopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, tx, ty, opts, vx, vy); % nntrain takes validation set as last two arguments (optionally)[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');```[![Bitdeli Badge](https://d2weczhvl823v0.cloudfront.net/rasmusbergpalm/deeplearntoolbox/trend.png)](https://bitdeli.com/free "Bitdeli Badge")

C++——文件操作

C++中输入输出是通过流对象进行操作,对于文件来说写文件就是将内容从程序输出到文件,需要用到写文件流ofstream;而读文件就是将内容从文件输入到程序,需要用到读文件流ifstream;这两个文件流类都包含在头文件中,对文件操作需要包含。

qq_42106610的博客 9705

c++ 读取 写入 文本文件

#include <iostream> #include <fstream> // 读写文件的头文件 #include <string> using namespace std; /* 1 文本文件 写文件 1 包含头文件 #include <fstream> 2 创建流对象 ofstream ofs; 3 指定路径和打开方式 ofs.ope...

WZY31014332886的专栏 471
上一篇: 3. C++入门:引用
下一篇: 4. C++入门:内联函数、auto关键字、范围for及nullptr
ChoSeitaku
博客等级 码龄5年 3452粉丝 557原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

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

抵扣说明:

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

余额充值