首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >如何正确地清空字符串缓冲区?

如何正确地清空字符串缓冲区?
EN

Stack Overflow用户
提问于 2020-11-21 13:14:32
回答 1查看 178关注 0票数 0

我读过如何清除字符串变量?来清除stringstream.str("")缓冲区,或者换句话说-设置空字符串。但如果我这么做了,它就不会被清除:

date.hpp

代码语言:javascript
运行
复制
#include <sstream>
#include <time.h>

#define fmt "%m/%d/%y"

class Date
{
    std::stringstream buffer;
    struct tm date;

    template <class T>
    void insertbuf(const T &);
    void inserttime();
    std::string getFromIn(std::istream &);

public:
    //ctors
    Date();
    Date(const char *str);
    Date(const std::string &s);
    Date(std::istream &in);
    Date(const Date &d);

    //operators
    Date &operator=(const Date &rhs);

    //general
    const std::string getAll() const;
    int getMonth() const;
    int getDay() const;
    int getYear() const;
};

date.cpp

代码语言:javascript
运行
复制
template <class T>
void Date::insertbuf(const T &val)
{
    if (!buffer.rdbuf()->in_avail())
    {
        buffer << val;
    }
}

void Date::inserttime()
{
    buffer >> std::get_time(&date, fmt);
}

Date &Date::operator=(const Date &rhs)
{
    if (&rhs != this)
    {
        buffer.str("");
        insertbuf<std::string>(rhs.buffer.str());
        inserttime();
    }
    return *this;
}

现在在函数insertbuf中,只有在没有其他数据的情况下,我才会将<<转到缓冲区。因此,在operator=中,它的左侧(对象本身,或*this)在缓冲区中有一些数据,因此我必须清除它们。我试图通过将缓冲区设置为空字符串buffer.str("")或等效的buffer.str(std::string())来做到这一点,但这似乎不会设置它。从这里:

main.cpp

代码语言:javascript
运行
复制
int main()
{
    Date bar = "11/23/2020";
    Date foo = "11/21/2020";
    cout << "before operator= " << foo.getAll() << endl;
    foo = bar;
    cout << "after operator= " << foo.getAll() << endl;
}

产出:

代码语言:javascript
运行
复制
before operator= date: 11/21/2020
after operator= date: 11/21/2020

正如我所看到的,在operator=函数中没有清除缓冲区,因为缓冲区没有改变(输出应该是11/23/2020insertbuf函数可能无法通过if statement,因为缓冲区不是空的,即使我将它设置为空字符串),为什么?那么如何正确清除std::stringstream的缓冲区呢?

一个例子:https://godbolt.org/z/h6zofr

问题背后的原因是:https://codereview.stackexchange.com/questions/252456/how-to-implement-simple-date-class-in-c

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2020-11-21 13:42:31

您遇到的问题是,调用buffer.str("")不会重置流状态标志,因此,如果以前的操作失败或到达流的末尾,其他任何读取都不会成功。以下应解决这一问题:

代码语言:javascript
运行
复制
buffer.str("");
buffer.clear();

您的代码似乎不必要地复杂。如果您要做的只是将日期转换为字符串,那么我建议使用Hinnant的日期库,这个库现在也是c++20的一部分。

票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/64943474

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档