【问题标题】:How to concatenate a string with chrono::milliseconds?如何用 chrono::milliseconds 连接字符串?
【发布时间】:2015-08-06 15:54:40
【问题描述】:

我需要一个带有时间戳的字符串,以毫秒为单位。 我以这种方式得到了毫秒数(在 stackoverflow 上找到它之后):

milliseconds ms = duration_cast< milliseconds >(
    system_clock::now().time_since_epoch()
);

现在我必须像这样连接它:

string = "something " + ms + " something else";

有什么帮助吗? 提前谢谢你:)

【问题讨论】:

    标签: c++ string chrono


    【解决方案1】:

    您需要一种将ms 转换为字符串的方法。该标准有std::to_string(),但这不会直接与持续时间一起工作。要将持续时间转换为to_string() 可以使用的整数类型,您需要使用count() 函数

    string = "something " + std::to_string(ms.count()) + " something else";
    

    【讨论】:

    • ms.count() 如果我将其打印为%llu 可以正常工作,但如果我尝试将std::to_string(ms.count()) 打印为%s 我会得到奇怪的字符,例如��
    • @Crisoberillo 你在用printf()吗?
    • (1/2) 在我的例子中,我可能过于简单化了。我正在使用 cocos2d-x 开发游戏。我需要处理一些网络通信,我必须实现的是格式化像"ts="+ timestamp + "&amp;a=move" 这样的字符串。
    • (2/2) 检查一些 cocos2d-x 指南和 stackoverflow,我在这一点上:const char* postData = ("ts="+ std::to_string(ms.count()) + "&amp;a=move").c_str();。我当前的问题是 postData 是空的,但是如果我用一个小的手动插入的整数替换 ms.count() ,它就可以正常工作。如果我使用的整数太大(6 位或更多),我又会得到一个空字符串。 10000 和 99999 都有效,但多了一个数字,比如 100000 和 999999 给了我空字符串问题。我希望它是可以理解的
    • @Crisoberillo 将字符串存储为 std::string,然后如果您需要 const char*,您可以随时调用 c_str()auto timestamp = "ts="+ std::to_string(ms.count()) + "&amp;a=move"; some_function(timestamp.c_str());
    【解决方案2】:

    使用count 方法和std::to_string。示例:

    string = "something " + std::to_string(ms.count()) + " something else"
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-02-12
      • 2015-07-21
      • 2021-08-23
      • 1970-01-01
      相关资源
      最近更新 更多