c++ - Boost 格式的字符串截断

标签 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());

最佳答案

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/

相关文章:

c++ - 从剪贴板获取文本后,需要将一个字符串插入另一个字符串的建议

java - 检查中间字符串是否以某种模式开始和结束并更新该字符串

Java:如何将从数据库返回的字符串转换为 XML

c++ - 使用头文件中定义的 vector 时出现 Unresolved external symbol 错误

c++ - 如何在 C++ 中追加字节数据?

c++ - 将多个数组槽设置为一个值的更简单方法

python - 如何在 python 中将 ascii 值列表转换为字符串?

c++ - 窗口 MFC : adjust child dialog to a tab control display area

javascript - else if 语句在变量分配中的效率

c++ - 将单个字符转换为 std::string prepends\x01