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

How to properly empty stringstream buffer?

我已阅读 How do you clear a stringstream variable? 通过 stringstream.str("") 清除缓冲区,或者换句话说 - 设置空字符串。但是如果我这样做,它不会清除它:

date.hpp:

#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:

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:

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;
}

输出:

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

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

buffer.str("");
buffer.clear();

您的代码似乎不必要地复杂。如果您只想将日期与字符串相互转换,我建议您使用 Howard Hinnant 的 date library which is now also part of c++20.