我读过如何清除字符串变量?来清除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/2020,insertbuf函数可能无法通过if statement,因为缓冲区不是空的,即使我将它设置为空字符串),为什么?那么如何正确清除std::stringstream的缓冲区呢?
一个例子:https://godbolt.org/z/h6zofr
问题背后的原因是:https://codereview.stackexchange.com/questions/252456/how-to-implement-simple-date-class-in-c
https://stackoverflow.com/questions/64943474
复制相似问题