这是我编写的一段简短代码,用于将以字符串或字符形式输入的时间打印为 hh:mm:ss 格式。 没有编译错误,但给出了垃圾值。它出什么问题了? 注意:我不想打印日/月/年。
# include<iostream>
# include<ctime>
using namespace std;
int main(){
const char *time_details = "15:34:12";
struct tm tm;
strptime(time_details, "%H:%M:%S", &tm);
time_t t = mktime(&tm);
cout << t << endl;
}
最佳答案
来自 strptime
的手册页:
If the format string does not contain enough conversion specifications to completely specify the resulting struct tm, the unspecified members of tm are left untouched.
您需要设置那些其他成员,或者只使用您设置的成员。
更新
这里的另一个问题是 mktime
的使用。从该函数的 OpenGroup 描述中,
If the time since the Epoch cannot be represented, the function shall return the value (time_t)-1
如果您简单地将结构 tm
置零,您将创建一个无法用 Unix 时间格式表示的时间(自 00Z,1970 年 1 月 1 日以来的秒数)。至少,您需要将年和月中的日期设置为非零值。
关于c++ - 尝试将存储在 char 中的时间转换为正常形式。打印一个随机值。怎么了?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11295460/