Boost格式的字符串截断

时间:2016-05-20 23:07:39

标签: c++ string

  • 我有这个代码用于打印当前日期。但是,当我打印它时,字符串被截断,我无法弄清楚为什么?

    • 因此,与“ 20-5 22-1-23 ”相反,我只得到“ 20-5 22 ”。

我认为发生了一些截断,但我无法弄清楚原因。

using namespace std; 
    const boost::posix_time::ptime now = boost::posix_time::second_clock::local_time();

    const boost::format f = boost::format("%d-%d %ld-%ld-%ld")
            % now.date().year_month_day().day.as_number()
            % now.date().year_month_day().month.as_number()
            //% now.date().year_month_day().year.as_number()
            % now.time_of_day().hours()
            % now.time_of_day().minutes()
            % now.time_of_day().seconds();

    const string result = f.str();
    snprintf(ret, sizeof(result.c_str()), "%s",  result.c_str());

1 个答案:

答案 0 :(得分:1)

snprintf有以下签名:

int snprintf ( char * s, size_t n, const char * format, ... );

其中n是Maximum number of bytes to be used in the buffer.但您提供:

sizeof(result.c_str())

在32位架构上的大小为4字节,在4位上的大小为8。您应该在此处提供缓冲区的大小:ret

这就是为什么你在"20-5 22"获得7个字符的原因,其中8个为\0