承接上一讲。

2.7文件I/O

关于读写文件,C++中有一个专门的头文件<fstream>。

首先是读文件演示样例,例如以下:

</pre><pre>

/*************************************************************************
> File Name: list1301_file.cpp
> Author: suool
> Mail: 1020935219@qq.com
> Created Time: 2014年05月22日 星期四 22时15分11秒
************************************************************************/ #include<cstdio>
#include<iostream>
#include<fstream>
#include<string> using namespace std; int main()
{
ifstream in ("list1301.txt");
if (not in )
{
perror("list1301.txt");
}
else
{
string x;
while(in >> x)
{
cout << x << endl;
}
in.close();
}
return 0;
}

文件内容:

读操作结果:

然后是写文件,示比例如以下:

/*************************************************************************
> File Name: list1302_write.cpp
> Author: suool
> Mail: 1020935219@qq.com
> Created Time: 2014年05月24日 星期六 12时24分23秒
> Aim at:Copying Integers from a Named File to a Named File
************************************************************************/ #include <cstdio>
#include <fstream>
#include <iostream> using namespace std; int main()
{
// Read data from file in
ifstream in("data.txt");
if (not in)
perror("data.txt"); // 文件不存在
else
{
ofstream out("out.txt"); // Write the data to out
if (not out)
perror("out.txt"); // 文件不存在
else
{
int x(0);
while (in >> x)
out << x << '\n';
out.close();
in.close(); // 关闭文件流
}
}
return 0;
}

文件内容例如以下:





执行结果:

watermark/2/text/aHR0cDovL2Jsb2cuY3Nkbi5uZXQvc3Vvb2w=/font/5a6L5L2T/fontsize/400/fill/I0JBQkFCMA==/dissolve/70/gravity/SouthEast" alt="">

只是上面的读写文件存在一定的问题。就是程序没有检查输出操作是否成功运行,以下的程序的改造就是带有最小错误检查的演示样例:

/*************************************************************************
> File Name: list1302_write_check.cpp
> Author: suool
> Mail: 1020935219@qq.com
> Created Time: 2014年05月24日 星期六 12时58分50秒
************************************************************************/ #include<iostream>
#include<string>
#include<fstream>
#include<cstdio>
using namespace std;
int main()
{
// read data from in
ifstream in("data.txt");
if(not in)
perror("data.txt");
else
{
ofstream out("out.txt");
if(not out)
perror("out.txt");
else
{
int x(0);
while(in >> x)
out << x<< endl;
out.close();
if(not out)
{
perror("ou.txt");
}
}
}
return 0;
}

就是这一部分:

watermark/2/text/aHR0cDovL2Jsb2cuY3Nkbi5uZXQvc3Vvb2w=/font/5a6L5L2T/fontsize/400/fill/I0JBQkFCMA==/dissolve/70/gravity/SouthEast" alt="">

2.8数据结构——映射

前面我们已经介绍并学习了C++的一个特有的数据结构——向量。如今我要介绍另外一个C++的特有数据结构——映射,其它的高级语言成称之为字典等,事实上都一样就是键值对的映射罢了。当中键是唯一的。值不限。

以下是一个演示样例:

/*************************************************************************
> File Name: list1401_data.cpp
> Author: suool
> Mail: 1020935219@qq.com
> Created Time: 2014年05月24日 星期六 13时17分39秒
************************************************************************/ // 读取单词并统计出现的次数
#include<cstdio>
#include<iomanip>
#include<ios>
#include<iostream>
#include<fstream>
#include<string>
#include<map> using namespace std;
int main()
{
map<string, int> counts;
string word; fstream in("data.txt");
if(not in)
{
perror("data.txt");
}
// Read words from the standard input and count the number of times
// each word occurs.
cout << "Read words from data.txt, spreate by blank space" << endl;
// For each word/count pair...
ofstream out("out.txt");
if(not out)
{
perror("out.txt");
}
while(in >> word)
{
++counts[word];
out << word << endl;
}
// out.close();
in.close();
cout << "The words and count are:" << endl;
out << "The words and count are:" << endl;
for (map<string,int>::iterator iter(counts.begin()); iter != counts.end(); ++iter)
{
// Print the word, tab, the count, newline.
cout << iter->first << '\t' << iter->second << '\n';
out << iter->first << '\t' << iter->second << '\n';
}
out.close();
if(not out)
{
perror("out.txt");
}
return 0;
}

数据文件依旧上面那个,结果例如以下:

下面一个演示样例是利用迭代器循环格式化输出映射内容:

/*************************************************************************
> File Name: list1401_data_compat.cpp
> Author: suool
> Mail: 1020935219@qq.com
> Created Time: 2014年05月24日 星期六 14时58分34秒
************************************************************************/ #include <iomanip>
#include <ios>
#include <iostream>
#include <map>
#include<fstream>
#include <string> // Aligning Words and Counts Neatly using namespace std; int main()
{
map<string, int> counts;
string word;
// read data from data.txt
fstream in("data.txt");
if(not in)
{
perror("data.txt");
} cout << "Read words from data.txt, spreate by blank space" << endl;
ofstream out("out.txt");
if(not out)
{
perror("out.txt");
}
// write data to out.txt
out << "Begin !!!! Hahahahahahahhaha" << endl;
while(in >> word)
{
++counts[word];
out << word << endl;
} // Determine the longest word.
string::size_type longest(0);
for (map<string,int>::iterator iter(counts.begin()); iter != counts.end(); ++iter)
if (iter->first.size() > longest)
longest = iter->first.size(); // For each word/count pair...
const int count_size(10); // Number of places for printing the count
out << "Hahahahahahahhaha!!!!" << endl;
for (map<string,int>::iterator iter(counts.begin()); iter != counts.end(); ++iter)
{
// Print the word, count, newline. Keep the columns neatly aligned.
cout << setw(longest) << left << iter->first <<
setw(count_size) << right << iter->second << '\n'; out << setw(longest) << left << iter->first <<
setw(count_size) << right << iter->second << '\n';
}
return 0;
}

文件内容:

执行结果:

watermark/2/text/aHR0cDovL2Jsb2cuY3Nkbi5uZXQvc3Vvb2w=/font/5a6L5L2T/fontsize/400/fill/I0JBQkFCMA==/dissolve/70/gravity/SouthEast" alt="">

以下一个样例是搜索映射中的指定键:

/*************************************************************************
> File Name: list1401_data_serach.cpp
> Author: suool
> Mail: 1020935219@qq.com
> Created Time: 2014年05月24日 星期六 15时17分30秒
************************************************************************/ #include<cstdio>
#include<fstream>
#include<iomanip>
#include<iostream>
#include<string>
#include<map> using namespace std;
int main()
{
map<string, int> counts;
string word; // read data from data.txt
ifstream in ("word.txt");
if(not in)
{
perror("word.txt");
}
// write data to out.txt
ofstream out ("out.txt");
if(not out)
{
perror("out.txt");
}
out << "Begin !!!! Hahahhahahah!!! \n";
while(in >> word)
{
++counts[word];
out << word << '\n';
}
out.close(); map<string, int>::iterator the(counts.find("the"));
if(the == counts.end())
cout << "\"the\" is not found!!!!" << endl;
else if(the->second == 1)
cout << "\"the\" occurs " << the->second << " time\n";
else
cout << "\"the\" occurs " << the->second << " times\n"; return 0;
}

文件内容:

执行结果:

watermark/2/text/aHR0cDovL2Jsb2cuY3Nkbi5uZXQvc3Vvb2w=/font/5a6L5L2T/fontsize/400/fill/I0JBQkFCMA==/dissolve/70/gravity/SouthEast" alt="">

未完待续。

。。。。。

。。

C++基础学习教程(三)的更多相关文章

  1. JavaScript 基础 学习(三)

    JavaScript 基础 学习(三) 事件三要素 ​ 1.事件源: 绑定在谁身上的事件(和谁约定好) ​ 2.事件类型: 绑定一个什么事件 ​ 3.事件处理函数: 当行为发生的时候,要执行哪一个函数 ...

  2. redis学习教程三《发送订阅、事务、连接》

    redis学习教程三<发送订阅.事务.连接>  一:发送订阅      Redis发布订阅(pub/sub)是一种消息通信模式:发送者(pub)发送消息,订阅者(sub)接收消息.Redi ...

  3. JAVA基础学习-集合三-Map、HashMap,TreeMap与常用API

    森林森 一份耕耘,一份收获 博客园 首页 新随笔 联系 管理 订阅 随笔- 397  文章- 0  评论- 78  JAVA基础学习day16--集合三-Map.HashMap,TreeMap与常用A ...

  4. java网络爬虫基础学习(三)

    尝试直接请求URL获取资源 豆瓣电影 https://movie.douban.com/explore#!type=movie&tag=%E7%83%AD%E9%97%A8&sort= ...

  5. C++基础学习教程(一)

    開始自己的C++复习进阶之路. 声明: 这次写的博文纯当是一个回想复习的教程.一些非常基础的知识将不再出现.或者一掠而过,这次的主要风格就是演示样例代码非常多~~~ 全部代码在Ubuntu 14.04 ...

  6. spring boot基础学习教程

    Spring boot 标签(空格分隔): springboot HelloWorld 什么是spring boot Spring Boot是由Pivotal团队提供的全新框架,其设计目的是用来简化新 ...

  7. salesforce 零基础学习(三十六)通过Process Builder以及Apex代码实现锁定记录( Lock Record)

    上一篇内容是通过Process Builder和Approval Processes实现锁定记录的功能,有的时候,往往锁定一条记录需要很多的限制条件,如果通过Approval Processes的条件 ...

  8. opengl基础学习专题 (三) 多边形绘制的几种样式

    题外话 聪明人之所以不会成功,是由于他们缺乏坚韧的毅力. ——艾萨克·牛顿(1643年1月4日—1727年3月31日)英国 也许可以理解为 想更深一步的时候,坚持,努力和聪明缺一不可. 挺直腰杆在此向 ...

  9. java基础学习总结三(jdk7新特性、变量(局部变量和成员变量)、常量以及运算符)

    一:jdk7新特性 可以表示二进制数值,以0b开头,中间可以使用下划线_分隔符.如下: @Test /** * 测试jdk新特性 */ public void testJdk7(){ int a=0b ...

随机推荐

  1. POJ--1087--A Plug for UNIX【Dinic】网络最大流

    链接:http://poj.org/problem? id=1087 题意:提供n种插座.每种插座仅仅有一个,有m个设备须要使用插座,告诉你设备名称以及使用的插座类型,有k种转换器.能够把某种插座类型 ...

  2. mysql改动用户password

    登录root用户 用root用户登录控制台. use mysql use mysql,mysql是mysql数据库自己主动创建的一个数据库. 改动user表的数据 update user set pa ...

  3. 本地自旋锁与信号量/多服务台自旋队列-spin wait风格的信号量

    周日傍晚,我去家附近的超市(...)买苏打水,准备自制青柠苏打.我感觉我做的比买的那个巴黎水要更爽口.由于天气太热,非常多人都去超市避暑去了,超市也不撵人,这仿佛是他们的策略.人过来避暑了,走的时候难 ...

  4. Gradle之依赖管理

    Gradle之依赖管理 泡在网上的日子 / 文 发表于2015-01-29 16:12 第8824次阅读 Gradle,Android Studio 2 编辑推荐:稀土掘金,这是一个针对技术开发者的一 ...

  5. c语言循环案例

    do while #include <stdio.h> #include <stdlib.h> int main() { int a = 1,b = 10; do { b -= ...

  6. Node.js:连接 MySQL

    ylbtech-Node.js:连接 MySQL 1.返回顶部 1. Node.js 连接 MySQL 本章节我们将为大家介绍如何使用 Node.js 来连接 MySQL,并对数据库进行操作. 如果你 ...

  7. nginx的安装步骤

    nginx学习资料;https://zhuanlan.zhihu.com/p/34943332 1.下载nginx的安装包:https://nginx.org/en/download.html 2. ...

  8. 利用CSS3中的clac()实现按照屏幕分辨率自适应宽度

    1.简介 calc()看其外表像个函数.平时在制作页面的时候,总会碰到有的元素是100%的宽度(例如body元素).如果元素宽度为100%时,其自身不带其他盒模型属性设置还好,要是有别的,那将导致盒子 ...

  9. Vmware 安装虚拟工具 (二)

    打开虚拟机,以root超级用户登陆,菜单栏选择虚拟机,install安装虚拟机 拷贝虚拟工具到 在根目录下建立文件夹,并将工具拷贝到该文件夹,例如vmtool 打开终端,进入该目录开始安装 如图,进入 ...

  10. Extjs Grid 各种Demo

    grid的一个渲染效果 Ext.define('cfWeb.view.accountSetting.OrgManageView',{ alias : 'widget.orgManageView', e ...