C++之“流”-第4课.重温文件流和字符串流

含两个视频。视频一讲解内存流(也就是字符串流)和文件流各自较为广泛的使用场景,视频二演练书中实践项目。(对应北京航天航空大学出版社的纸质书《白话C++ . 练武篇》 10.1.4 小节)。

这节课,我们重点学习C++标准库中的文件流(fstream) 和 字符串流(stringstream),后者也经常被视为 C++ 的内存流。

嗯,只要您想拥有操控系统的能力,那么,不管您使用哪一门计算机语言,文件、字符串、内存三者一个都不能少……但这不是重点,作为一名C++程序员,您还得学习:它们是怎么,以及为什么和“流”扯上了关系?
www.d2school.com-C++之文件流与字符串流

一、“流”的理论讲解

本课例程中,文件流使用了 ifstream 和 ofstream,而字符串流使用了 stringstream 。这么安排的原因是因为,这正是文件流和字符串流(也称为内存流)比较常见的用法。为什么?请看视频1。

C++之“流”-第4课上:重温文件流和字符串流-理论

二、“流”的上机实践

接下来是具体的上机操作过程实录,请看视频2:

C++之“流”-第4课:重温文件流和字符串流-之二(上机)

三、完整源码

#include <iostream>
#include <fstream>
#include <sstream> //stringstream

#include <list>
#include <vector>

using namespace std;

template<typename Iter>
void output(Iter const& beg, Iter const& end)
{
    for (auto it = beg; it != end; ++it)
    {
        cout << *it << endl;
    }
}

void foo()
{
    stringstream bufss;

    bool is_first = true;

    do
    {
        // 1、从控制台读入一个单词(不含空格)
        cout << "please input a word: ";
        string word;

        cin >> word;

        // 3、使用空格拼接每个单词,直到读入 "end"
        if (word == "end")
        {
            break;
        }

        if (!is_first)
        {
            bufss << ' '; // 使用空格拼接
        }
        else
        {
            is_first = false;
        }

        // 2、把读到的单词输出到内存流
        bufss << word; // bufss 作为 输出流
    }
    while(true);

    // 4、将内存流中的内容,以字符串的形式,整体输出到屏幕
    cout << "buffer :\n";
    cout << bufss.str() << endl;

    // 5、从内存流中读出单词,偶数下标单词存入list,奇数下标单词存入vector
    list<string> lst;
    vector<string> vec;

    int count = 0;

    while(!bufss.eof()) // eof : 输入流,是否结束
    {
        string word;
        bufss >> word; // 作为输入流

        if (count % 2 == 0)
        {
            lst.push_back(word);
        }
        else
        {
            vec.push_back(word);
        }

        ++count;
    }

    // 6、将list和vector内的单词,输出到屏幕:
    cout << "list:\n";
    output(lst.cbegin(), lst.cend());
    cout << "vector:\n";
    output(vec.cbegin(), vec.cend());

    // 7、将list和vector中的单词交替输出到同一文件
    string filename = "strings.txt";
    ofstream ofs (filename);

    auto itLst = lst.cbegin();
    auto itVec = vec.cbegin();

    for (; itLst != lst.cend(); ++itLst, ++itVec)
    {
        ofs << *itLst << endl;
        if (itVec != vec.cend())
        {
            ofs << *itVec << endl;
        }
    }

    ofs.close();

    // 8、读出文件中的单词,再次显示到屏幕上
    ifstream ifs(filename);

    if (!ifs)
    {
        cout << "file no found " << filename << endl;
        return;
    }

    cout << "read from file:\n";

    while(!ifs.eof())
    {
        string word;
        ifs >> word;

        cout << word << endl;
    }
}

int main()
{
    foo();
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

南郁

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值