C++输入输出流

输入输出流

  • 说明:IO对象无拷贝或者赋值的操作,有许多标志位,可以判断当前IO的状态

控制台输入输出

  • 主要是cincout
  • 标准库将cincout关联在一起,当使用cin的时候,cout的缓冲区也会被刷新

文件输入输出

文件模式

  • 分类
    • in:以读方式打开
    • out:以写的方式打开
    • app:每次写操作前,都定位到文件末尾
    • ate:打开文件后,立刻定位到文件末尾
    • trunc:截断文件
    • binary:以二进制方式运行io
  • 说明
    • 只有对ofstream或者fstream对象设定out模式
    • 只有对ifstream或者fstream对象设定in模式
    • out模式也被设定时,才能设定trunc模式
    • 只使用out模式,会覆盖掉原始文件中的内容
  • 注意:使用open函数可以打开输入输出流,使用close可以进行关闭,当然,对于声明的变量,可以因为对象被销毁而关闭,但是还是建议尽量手动关闭,防止后续的误操作
  • 代码

    void test()
    {
        vector<string> words;
        string s;
        char ch[1024];
        ifstream infile("text.txt", ios::in);
        ofstream ofile("sentence.txt", ios::out);
        if (ofile)
        {
            // 按行读入
            while (infile.getline(ch, 1024))
            {
                cout << ch << endl;
                ofile << ch << endl;
            }
            infile.close();
            ofile.close();
        }
    
        infile.open("text.txt", ios::in);
        ofile.open("words.txt", ios::out);
        if (ofile)
        {
            // 按单词读入(遇到空格、换行、制表符等都会视为一个单词的结束)
            while (infile >> s)
            {
                cout << s << endl;
                ofile << s << endl;
            }
            infile.close();
            ofile.close();
        }
    }
    

string流

简介

  • sstream头文件中定义了三个类,用于支持内存IO,istringstream从string读入数据,ostringstream向string写入数据,stringstream支持上面两种操作
  • 代码

    void test()
    {
        vector<string> words;
        string s;
        char ch[1024];
        ifstream infile("contact.txt", ios::in);
    
        unordered_map<string, vector<int>> infos;
    
        while (getline(infile, s))
        {
            string key;
            vector<int> vec;
            int tmp = 0;
            istringstream is(s);
            is >> key; // 构造一个包含字符串的读入缓冲区,然后可以从这个缓冲区中读取所需要的信息
            while (is >> tmp)
            {
                vec.push_back(tmp);
    
            }
            infos[key] = vec;
            cout << s << endl;
        }
        cout << "=====infos======" << endl;
        ostringstream os;
        for (auto it = infos.begin(); it != infos.end(); it++)
        {
            os << "key is : " << it->first << ", value is : ";
            for (auto & num : it->second)
                os << num << " ";
            cout << os.str() << endl;
            os.str("");
            //os.clear(); //这句话只是清空缓冲区的标志位,并没有清空缓冲区的内容
        }
    
    }
    
  • contact中的内容

    AA 1 4 7
    BB 2 5 8
    CC 3 6 9
    

猜你喜欢

转载自blog.csdn.net/u012526003/article/details/80173721