我想我在某处读到如果我将nullptr传递给std :: strftime,该函数将返回所需的缓冲区大小.事实上,以下代码在我尝试过的众多Linux系统上运行得非常好(不是在使用VS编译时):
#include <iostream>
#include <ctime>
#include <string>
int main()
{
std::time_t time{};
std::tm const * ltime = std::localtime(&time);
const char * formatString = "%Y-%b-%d";
//allocate buffer of appropriate size
auto requiredSize = 1 + std::strftime(nullptr, 50, formatString, ltime);
std::cout << "Required buffer size:" << requiredSize << "\n";
//Format time to string
std::string buff(requiredSize, ' ');
std::strftime(&buff[0], requiredSize, formatString, ltime);
std::cout << buff << std::endl;
}
Run Code Online (Sandbox Code Playgroud)
但是,我无法找到我的原始源或任何其他指定此行为的文档.所以我的问题是:
编辑:我添加了C标签,因为我已经看到了相同的C代码相同的结果,至少使用gcc/g ++(或者更确切地说是glibc/libstdc ++)std::strftime可能只是c函数的别名strftime.