C++:ostringstream如何清空

今天写C++Primer IO部分8.13题的时候,代码是这样写的:

#include<iostream>
#include<fstream>
#include<sstream>
#include<string>
#include<vector>

using std::cout;
using std::cin;
using std::endl;
using std::fstream;
using std::istringstream;
using std::ostringstream;
using std::string;
using std::vector;
using std::begin;
using std::end;

struct PersonInfo
{
    string strName;
    vector<string> vecStr;
};

int main()
{
    vector<PersonInfo> vecPer;
    PersonInfo per;
    fstream ifs("./infile.txt",fstream::in);
    fstream ofs("./outfile.txt",fstream::out);
    istringstream iss;
    ostringstream oss;
    string str;
    while(getline(ifs,str))
    {
        iss.str(str);
        iss>>str;
        per.strName = str;
        while(iss>>str)
        {
            per.vecStr.push_back(str);
        }
        vecPer.push_back(per);
        per.vecStr.clear();
        iss.clear();
    }
    for(const auto &perInfo:vecPer)
    {
        
        oss << perInfo.strName<<" ";
        if(perInfo.vecStr.size())
        {
            for(const auto &strNum:perInfo.vecStr)
            {
                oss<<strNum<<" ";
            }
        }
        else 
        {
            oss <<"DataWrong";
        }
        ofs<<oss.str()<<endl;
    }
    
    return 0;
}

但是输出的时候,outfile.txt文件上是这样的:

这显然不是想要的结果。结果应该是一个人一行才对。

但这个答案的原因也很容易想到,一定是因为持续想oss中输出,而oss之前的串还在,所以就连在了一起,只需要每次输出之前清空oss即可。

可是C++Primer这部分并没有讲如何清空这个ostringstream的缓冲,显然不可能使用clear()。

所以我就想到了赋值,在每次输出之前先为其绑定一个string对象,然后再进行输出(因为我使用的模式是out,所以每次绑定都会对其进行清空)。

代码如下:

#include<iostream>
#include<fstream>
#include<sstream>
#include<string>
#include<vector>

using std::cout;
using std::cin;
using std::endl;
using std::fstream;
using std::istringstream;
using std::ostringstream;
using std::string;
using std::vector;
using std::begin;
using std::end;

struct PersonInfo
{
    string strName;
    vector<string> vecStr;
};

int main()
{
    vector<PersonInfo> vecPer;
    PersonInfo per;
    fstream ifs("./infile.txt",fstream::in);
    fstream ofs("./outfile.txt",fstream::out);
    istringstream iss;
    ostringstream oss;
    string str;
    while(getline(ifs,str))
    {
        iss.str(str);
        iss>>str;
        per.strName = str;
        while(iss>>str)
        {
            per.vecStr.push_back(str);
        }
        vecPer.push_back(per);
        per.vecStr.clear();
        iss.clear();
    }
    for(const auto &perInfo:vecPer)
    {
        oss.str(str);
        oss << perInfo.strName<<" ";
        if(perInfo.vecStr.size())
        {
            for(const auto &strNum:perInfo.vecStr)
            {
                oss<<strNum<<" ";
            }
        }
        else 
        {
            oss <<"DataWrong";
        }
        ofs<<oss.str()<<endl;
    }
    
    return 0;
}

运行之后,outfile.txt文件如图:

哈哈,看来果然是可行的。

原文地址:https://www.cnblogs.com/FWFC/p/8603253.html