如何将 put_time 放入变量中

hel*_*llo 5 c++

我有一个功能

transTime() 
{ 
  time_t const now_c = time(NULL); 
  cout << put_time(localtime(&now_c), "%a %d %b %Y - %I:%M:%S%p"); 
} 
Run Code Online (Sandbox Code Playgroud)

我正在尝试将返回的值保存到变量中,以便我可以执行类似的操作

string myTime = put_time(localtime(&now_c), "%a %d %b %Y - %I:%M:%S%p"); 
Run Code Online (Sandbox Code Playgroud)

我需要对两个不同的插入使用同一个 myTime 实例。

编辑/更新:

使用字符串流后,

string transTime()
{
   stringstream transTime;
   time_t const now_c = time(NULL);
   transTime << put_time(localtime(&now_c), "%a %d %b %Y - %I:%M:%S%p");
   string myTime = transTime.str();
  //transTime >> myTime;
   return  myTime;
}
Run Code Online (Sandbox Code Playgroud)

当我使用 call 函数时,我Tue独自一人,而不是完整的日期和时间。很可能与 getline 有关,不确定如何实现。有什么帮助吗?

sha*_*ats 5

当您使用 astringstream捕获 的输出时,您可以使用 来localtime()存储存储在 中的字符串。stringstream.str()

那是,

string myTime = transTime.str();
return myTime;
Run Code Online (Sandbox Code Playgroud)


Gus*_*uss 5

一些 C++ API 可以使用更多的调用约定一致性(1) - 它看起来std::put_time()只适用于流,因为它是用于本地化的 - 因此它可以利用注入流中的区域设置,所以虽然很容易使用 - 它实际上并不适合本地化流上下文之外的一般消费。

本质上,调用std::put_time()应该提供与调用相同的输出std::strftime- 尽管后者有一个更烦人的 API(参见(1)),而且我一生都无法理解为什么它不能只返回正确大小的std::string对象(与其他 API 一样,例如std::to_string())。

话虽如此,这里有一个稍微不那么烦人的方法来使用 C++ 标准库日期时间格式来创建std::strings:

std::time_t t = std::time(nullptr);
std::string datetime(100,0);
datetime.resize(std::strftime(&datetime[0], datetime.size(), 
    "%a %d %b %Y - %I:%M:%S%p", std::localtime(&t)));
Run Code Online (Sandbox Code Playgroud)

确保100(或您输入的任何内容)对于您的格式有足够的字符,否则您会得到一个空字符串。strftime不允许您检查需要多少空间,除非迭代(再次参见(1))。

顺便说一句 - 在光明的 C++20 未来(2)我们可以简单地(3)做:

using std::chrono::seconds, std::chrono::days;
auto time = std::chrono::floor<seconds>(std::chrono::system_clock::now());
auto today = std::chrono::floor<days>(time);
std::string datetime = std::format("{0:%a %d %b %Y} - {1:%H:%M:%S}",
                                   std::chrono::year_month_day{today},
                                   std::chrono::hh_mm_ss{time - today});
Run Code Online (Sandbox Code Playgroud)

但据我所知,目前还没有任何地方可以使用此功能。

笔记:

  1. 为什么std::localtime()采用指针而不是引用完全超出了我的理解,它需要您编写更多的代码并处理比需要的更多的临时变量。std::put_time()不需要您预先分配内存,但std::strftime()可以实现完全相同的功能。
  2. 参见P1361R2
  3. 对于某些“简单”的值。