【问题标题】:How to add current time to a string concisely in C++?如何在 C++ 中简洁地将当前时间添加到字符串中?
【发布时间】:2014-07-20 03:07:36
【问题描述】:

我想在这部分代码的文件名中添加一个时间戳:

takeScreenshot( "screenshot.png" );

但我发现的所有执行此操作的方法似乎都不必要地冗长和复杂。例如。创建一个新字符串,加载一个时间结构体,将时间结构体的一个元素转换为一个字符数组并将其附加到字符串中。

有没有捷径可以做到这一点?大多数其他语言都有一些简单的解决方案,例如:

takeScreenshot( sprintf( "screenshot-%d.png", time() ) );

在 C++ 中有一个吗?时间格式无关紧要。

【问题讨论】:

    标签: c++ string time


    【解决方案1】:

    串联一个字符串 又长又复杂,在后台。

    一个不错的方法是使用std::stringstream 重载<< 进行连接:

    std::stringstream ss;
    ss << "screenshot-" << time() << ".png";
    std::string s = ss.str();
    

    并根据个人喜好格式化time()

    【讨论】:

    • 不要忘记添加“sstream.h”头文件..!
    【解决方案2】:

    你可以使用 stringstream 或者只在字符串之间使用 + 运算符:

    takeScreenshot("screenshot-" + time() + ".png");
    

    【讨论】:

    • "this is not a std::string and it cannot be added"
    • 你也可以试试 boost::lexical_cast<:string>
    猜你喜欢
    • 2013-01-27
    • 2010-11-28
    • 2015-04-28
    • 1970-01-01
    • 2012-11-21
    • 2023-03-17
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多