我有这段代码可以用来打印当前日期。但是,当我打印它时,字符串被截断了,我不知道为什么?
- 因此,与得到“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());
最佳答案
snprintf具有以下签名:
int snprintf ( char * s, size_t n, const char * format, ... );
其中 n 是 缓冲区中要使用的最大字节数。
但您提供:
sizeof(result.c_str())
在 32 位架构上大小为 4 个字节,在 4 位架构上大小为 8 个字节。您应该在此处提供缓冲区的大小:ret
。
这也是为什么你在 "20-5 22"
中得到 7 个字符,八个是 \0
关于c++ - Boost 格式的字符串截断,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37357114/