body, table{font-family: 微软雅黑; font-size: 10pt}
table{border-collapse: collapse; border: solid gray; border-width: 2px 0 2px 0;}
th{border: 1px solid gray; padding: 4px; background-color: #DDD;}
td{border: 1px solid gray; padding: 4px;}
tr:nth-child(2n){background-color: #f8f8f8;}

C++语言的输入输出机制包含3层,前两层是从传统的C语言继承而来,分别是底层I/O和高层I/O,第3层是C++中增添的流类库,重点

      (1)底层I/O:底层I/O依赖于操作系统来实现,调用操作系统的功能对文件进行输入输出处理,具有较高的速度。底层I/O将外部设备和磁盘文件都等同于逻辑文件,采用相同的方法进行处理,一般过程为“打开文件”、“读写文件”,“关闭文件”,这些是通过一组底层I/O函数来完成的,这些函数定义在头文件io.h中2016/11/8 12:13:19。
     

(2)高层I/O:高层I/O是在底层I/O的基础上扩展起来的,仍旧将外部设备和磁盘文件统一处理,但处理的方式更为灵活,提供的一组处理函数定义在头文件stdio.h中,新的C++标准头文件为<cstdio>,提供的这些函数大体可分为两类:一般文件函数(外部设备和磁盘文件)和标准I/O函数。

      (3)流类库:除了从C语言中继承了上述两种I/O机制外,C++还特有一种输出机制:流类库(即iostream类库),这是C++所特有的,iostream类库为内置类型对象提供了输入输出支持,也支持文件的输入输出,另外,类的设计者可以通过运算符重载机制对iostream库的扩展,来支持自定义类型的输入输出操作。
// iostream  继承层次
---------------------------------------------------------------------------------------
流的分类:

1. 标准输入输出流 -- 头文件<iostream>
cin/cout/cerr-- printf/scanf
2.文件输入输出流 -- 头文件<fstream>
ifstream/ofstream/fstream
fprintf   fscanf 
3. 字符串流 -- 头文件<sstream>
istringstream/ostringstream/stringstream
sscanf  sprintf
---------------------------------------------------------------------------------------
标准输入输出流:
 流的状态:
badbit          系统级故障,不可恢复
failbit           可以恢复的错误
eofbit           碰到了文件结尾
goodbit        有效状态
查询流的状态:
cin.bad()
cin.fail()
cin.eof()
cin.good()
重置状态  cin.clear()
#include<iostream>
#include<string>
#include<limits>
using namespace std;
void print_cin()
{
        cout<<"badbit="<<cin.bad()<<endl;
        cout<<"failbit="<<cin.fail()<<endl;
        cout<<"eofbit="<<cin.eof()<<endl;
        cout<<"goodbit="<<cin.good()<<endl;
}
int main()
{
        print_cin();
        cout<<endl;
        int num;
        while(cin>>num)
                cout<<"num="<<num<<endl;
        print_cin();
        cout<<endl;
        cin.clear();
        print_cin();
        cout<<endl;
        //cin.ignore(numeric_limits<streamsize>::max(),'\n');    
        //不加这句话,下面语句就会把刚才错误输入的字符串直接输出来
        cin.ignore(1024,'\n');         
        //同上,表示最多忽略1024个字符,期间遇到'\n'就开始执行下面语句
        string s;
        cin>>s;
        cout<<s<<endl;
        return 0;
}
#include<iostream>
#include<limits>
using namespace std;
int main()
{
        int num;
        while(cin>>num,!cin.eof())
        {
                if(cin.good())
                {
                        cout<<"num="<<num<<endl;
                }
                if(cin.fail())
                {
                        cout<<"data error,try again"<<endl;       
                        cin.clear();
                        cin.ignore(numeric_limits<streamsize>::max(),'\n');
                        //cin.clear();  会出现死循环,必须在ignore前面使用
                }
        }
        return 0;
}

//设置忽略3个字符                                                            //没加ignore                                                                     //正常预期效果
           
----------------------------------------------------------------------------------------------------------------------------
文件输入输出流  <fstream>
ifstream         文件输入流
ofstream        文件输出流
fstream          二者兼有
#include<iostream>
#include<string>
#include<fstream>
#include<vector>
using namespace std;
int main()
{
        ifstream in("file");
        if(!in.good())
        {
                cout<<"open file fail!"<<endl;
                return -1;
        }
        vector<string> vec;
        vec.reserve(10);
        string str;
        while(getline(in,str))
                cout<<str<<endl;
               // vec.push_back(str);
        cout<<endl;
        in.close();
        return 0;
}
使用迭代器
vector<string>::iterator p;
#if 1
        for(p=vec.begin();p!=vec.end();p++)
        {
                cout<<*p<<endl;
        }
#endif

#include <iostream>
#include<string>
#include<fstream>
using namespace std;
int main()
{
        ifstream in("file");    //要求文件事先存在
        if(!in.good())
        {
                cout<<"open file fail!"<<endl;
                return -1;
        }
        ofstream out("file1");   //对文件存不存在没有要求
        if(!out.good())
        {
                cout<<"open file1 fail!"<<endl;
                return -1;
        }
        string str;
        while(getline(in,str))
        {
                out<<str<<endl;
        }
        in.close();
        out.close();
        return 0;
}

#include<iostream>
#include<fstream>
using namespace std;
int main()
{
        fstream io("file") ;             //要求文件事先存在
        if(!io.good())
        {
                cout<<"open file fail!"<<endl;
                return 0;
        }
        int num;
        for(int i=0;i!=10;i++)
        {
                cin>>num;
                io<<num<<" ";
        }
        io<<endl;
        cout<<endl;
        cout<<"io.tellp()="<<io.tellp()<<endl<<endl;   //tellp()ifstream对象特有
        io.seekp(0,ios::beg);
        for(int i=0;i<10;i++)
        {
                io>>num;
                cout<<num<<" ";
        }
        cout<<endl<<endl;
        cout<<"io.tellg()="<<io.tellg()<<endl;   //tellg(),ofstream对象特有
        return 0;
}




文件模式
ios::in               打开文件做读操作
ios::out             打开文件做写操作,会删除原有数据
ios::app           在每次写之前找到文件尾                            //只对输出流起作用<<
ios::trunc          打开文件时清空已存在的文件流
ios::ate            打开文件后立即定位到文件末尾                   //只对输入流起作用>>
ios::binary         以二进制模式进行IO操作
ios::beg            文件流指针定位到文件开头
字符串输入输出流  <sstream>
//把非字符串的数据转换成字符串时就使用它类似sprintf();      //字符串拼接
istringstream
ostringstream
stringstream
#include <iostream>
#include<sstream>
#include<string>
#include<stdio.h>
#include<string.h>
using namespace std;
void sprint(int a,int b)
{
        char arr[100];
        memset(arr,0,sizeof(arr));
        sprintf(arr,"%d,%d",a,b);
        cout<<arr<<endl;
}
string ostring(int a,int b)    //这里字符串,整形都可以
{
        ostringstream oss;
        //stringstream oss;    //一样的效果
        oss<<a<<","<<b;
}
void istring(string line)
{
        istringstream iss(line);
        //stringstream iss(line); 
        string world;
        while(iss>>world)
        {
                cout<<world<<endl;
        }
}
int main()
{
        int a=512;
        int b=1024;
        sprint(a,b);
        cout<<endl;
        string s = ostring(a,b);
        cout<<s<<endl<<endl;
        string s1 = "hello world shen zhen";
        istring(s1);
        return 0;
}

3. 统计一篇英文(The_Holy_Bible.txt)文章中出现的单词和词频,
   输入:某篇文章的绝对路径
   输出:词典(词典中的内容为每一行都是一个“单词 词频”)
-----------------
|   a 66          |
|   abandon 77    |
|   public 88     |
|    ......              |
|_________________|
        class WordStatic
        {
        public:
            void read_file(std::string filename);
            void write_file(std::string filename);
        private:
            //......
        };

#include <iostream>
#include<fstream>
#include<vector>
#include<string>
#include<string.h>
#include<iomanip>
using namespace std;
class WordStatistic
{
        private:
                vector<string> word;
                vector<int> count;
        public:
                void read_file(string filename);
                void write_file(string filename);
};
void WordStatistic::read_file(string filename)
{
        char name[100];   //这里不能定义指针,不然段错误
        strcpy(name,filename.c_str());
        ifstream in(name);
//括号里面的参数必须是const char*
        if(!in.good())
        {
                cout<<"open file fail!"<<endl;
                return ;
        }
        cout<<"正在统计文件……"<<endl;
        string tmpword;       
        while(in>>tmpword)
        { 
                if(tmpword[0]>='0'&&tmpword[0]<='9')
                        continue;
                int vecwordsize=word.size();
                int i;
                for(i=0;i<vecwordsize;i++)
                {
                        if(word[i].compare(tmpword)==0)
                        //if(vers[idx]==tmpword)  
                        {
                                count[i]++;
                                break;
                        }
                }
                if(i==vecwordsize)
                {
                        word.push_back(tmpword);
                        count.push_back(1);
                }
        }
        in.close();
        cout<<"统计结束!"<<endl;
}
void WordStatistic::write_file(string filename)
{
        char name[100];
        strcpy(name,filename.c_str());
        ofstream out(name);
        cout<<"统计结果正在写入文件……"<<endl;
        if(out.good()==0)
        {
                cout<<"open outfile fail!"<<endl;
                return ;
        }
        for(int i=0;i<word.size();i++)
        {
                out<<setw(20)<<word[i]<<setw(15)<<count[i]<<endl;
        }
        out.close();
        cout<<"写入结束!"<<endl;
}

int main()
{
        WordStatistic WS;
        WS.read_file("The_Holy_Bible.txt");
        WS.write_file("统计结果.txt");
        return 0;
}

I/O流+统计文件词频的更多相关文章

  1. java IO流 对文件操作的代码集合

    Io流 按照分类 有两种分类 流向方向: 有输入流和输出流 按照操作类型有:字节流和字符流 按照流向方向 字节流的一些操作 //读文件 FileInputStream fis = new FileIn ...

  2. week12 201621044079 流与文件

    作业12-流与文件 1. 本周学习总结 1.1 以你喜欢的方式(思维导图或其他)归纳总结多流与文件相关内容. 2. 面向系统综合设计-图书馆管理系统或购物车 使用流与文件改造你的图书馆管理系统或购物车 ...

  3. Java笔记13:统计文件中每个字符出现的次数

    一.代码实现 import java.io.*; import java.util.*; /** 功能:统计文件中每个字符出现的次数 思路: 1.定义字符读取(缓冲)流 2.循环读取文件里的字符,用一 ...

  4. 利用fgetc统计文件所在字节 和 总行数 和单词数

    #include <stdio.h> #include <stdlib.h> #define IS_WHITE_SPACE(c) ((c)==' '||(c)=='\t'||( ...

  5. Java:IO流与文件基础

    Java:IO流与文件基础 说明: 本章内容将会持续更新,大家可以关注一下并给我提供建议,谢谢啦. 走进流 什么是流 流:从源到目的地的字节的有序序列. 在Java中,可以从其中读取一个字节序列的对象 ...

  6. C++之流与文件

    C++中,输入输出采用流来进行,例如iostream库中的 cin 和 cout .对文件进行读写操作也使用流.可以将文件与流关联起来,然后对文件进行操作.要将流与文件关联起来,必须像声明变量那样声明 ...

  7. java io流 对文件夹的操作

    java io流 对文件夹的操作 检查文件夹是否存在 显示文件夹下面的文件 ....更多方法参考 http://www.cnblogs.com/phpyangbo/p/5965781.html ,与文 ...

  8. java io流 创建文件、写入数据、设置输出位置

    java io流 创建文件 写入数据 改变system.out.print的输出位置 //创建文件 //写入数据 //改变system.out.print的输出位置 import java.io.*; ...

  9. java io流(字符流) 文件打开、读取文件、关闭文件

    java io流(字符流) 文件打开 读取文件 关闭文件 //打开文件 //读取文件内容 //关闭文件 import java.io.*; public class Index{ public sta ...

随机推荐

  1. org.springframework.beans.factory.CannotLoadBeanClassException: Cannot find class [com.my.service.ProductService] for bean with name 'productService' defi报错解决方法

    原 javaweb项目报错org.springframework.beans.factory.CannotLoadBeanClassException: Cannot find class [XXX] ...

  2. U盘在制作Ubuntu启动盘后Windows系统下显示空间不对的解决办法(Ubuntu系统下格式化U盘的方法)

    用Ubuntu系统自带的启动盘制作工具后,将U盘拿到Windows系统下使用显示出的空间与U盘大小不同. 解决该问题的办法: 使用Linux终端: 第一步:sudo fdisk -l 这个命令主要是查 ...

  3. Labview 查看一次while循环运行的时间

    在while循环中增加一个移位寄存器,移位寄存器的初始值使用时间计数器,在while循环里面增加一个减法Vi,再增加一个时间计数器,两者做差,最后显示差值. 在这里只能显示大概运行时间.如下图.

  4. [BZOJ1044木棍分割]

    Description 有n根木棍, 第i根木棍的长度为Li,n根木棍依次连结了一起, 总共有n-1个连接处. 现在允许你最多砍断m个连 接处, 砍完后n根木棍被分成了很多段,要求满足总长度最大的一段 ...

  5. js初步用法

    js js引入方式:  1.方式一   通过script标签引入 2.方式二   通过script标签引入 ,src属性 引入一个外部的js文件 注意: 如果你使用了script标签的src属性 那么 ...

  6. 【Network Architecture】Densely Connected Convolutional Networks 论文解析

    目录 0. Paper link 1. Overview 2. DenseNet Architecture 2.1 Analogy to ResNet 2.2 Composite function 2 ...

  7. java 连接 redis集群时报错:Could not get a resource from the pool

    由于弄这个的时候浪费了太多的时间,所以才记录下这个错,给大伙参考下 检查了一下,配置啥的都没问题的,但在redis集群机器上就可以,错误如下: Exception in thread "ma ...

  8. python 匹配中文和英文

    在处理文本时经常会匹配中文名或者英文word,python中可以在utf-8编码下方便的进行处理. 中文unicode编码范围[\u4e00-\u9fa5] 英文字符编码范围[a-zA-Z] 此时匹配 ...

  9. 实现表单checkbox获取已选择的值js代码

    <input type="checkbox" name="cb" value="1" />aa <input type=& ...

  10. LA 7272 Promotions(dfs)

    https://vjudge.net/problem/UVALive-7272 题意: 公司要提拔人,现在有n个人,现在有m条有向边,A->B表示A的表现比B好,也就是如果B晋升了,那么A肯定会 ...