如何在不反复试验的情况下为 strftime 调整 char 数组的大小?使用 mktime,示例中的时间戳大小 N 必须大于 86,否则我会返回任意日期。 例如
N = 86:2013-07-13 02:41
N = 82:1979-05-18 13:23
如何在事先不知道日期的情况下有效地缩放 N?检查 >0 没有帮助。
#include <iostream>
#include <cstring>
#include <ctime>
#define N 86
using namespace std;
int main(void)
{
time_t t;
struct tm ts;
char timestamp[N] ;
ts.tm_min = 41;
ts.tm_hour = 2;
ts.tm_mday = 13;
ts.tm_mon = 7 - 1;
ts.tm_year = 13 - 1900 + 2000;
t = mktime(&ts);
if (strftime(timestamp, sizeof(timestamp)-1, "%Y-%m-%d %H:%M", &ts) > 0)
cout << timestamp;
else {
cerr << "strftime failed." <<endl;
return 1;
}
return 0;
}
最佳答案
来自 strftime 的文档:
If the length of the resulting C string, including the terminating null-character, doesn't exceed maxsize, the function returns the total number of characters copied to ptr (not including the terminating null-character). Otherwise, it returns zero, and the contents of the array pointed by ptr are indeterminate.
这意味着如果您不知道大小并且可以动态分配一个字符串,您可以按照以下方式做一些事情:
int size = N; // Some starting size
char *timestamp = malloc(size);
// Your time stuff
int result = strftime(timestamp, size - 1, "%Y-%m-%d %H:%M", &ts);
// While there isn't enough room to store the result
while (result == 0)
{
free(timestamp); // Free old data
size *= 2; // Double the size (should be more than enough)
timestamp = malloc(size); // Allocate the new size. You can check for failed allocations here as well.
// Retry
result = strftime(timestamp, size - 1, "%Y-%m-%d %H:%M", &ts);
}
std::cout << timestamp;
关于c++ - 确定 strftime char 数组的最大大小的智能方法是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30269657/