我有以下代码:
#include <ctime>
#include <stdio.h>
#include <iostream>
#include <chrono>
using namespace std;
const std::string currentDateTime() {
time_t now = time(0);
struct tm tstruct;
char buf[80];
tstruct = *localtime(&now);
strftime(buf, sizeof(buf), "%X", &tstruct);
return buf;
}
int main() {
std::cout << "Current Time is: " << currentDateTime() << std::endl;
return 0;
}
我编译这个,我得到:当前时间是:18:30:11
我想知道如何将其转换为整数,使其显示为 18.5 或类似的东西。我想这样做是因为我想创建一个时间表。
示例:如果是 10:30,我希望程序能够告诉我我有什么科目(学校)。
像这样:
if(time == 10.5)
std::cout<<(subject);
关于如何做到这一点有什么建议吗?我是 c++ 的新手,我不确定我是否以完全错误的方式处理这个问题。还有另一种方法吗? 提前致谢。
最佳答案
我想您的意思是将时间转换为 float 。在您的 currentDateTime
函数中,您已经使用了 struct tm
。基于此,您可以通过以下方式获得 float
小时值:
time_t now = time(0);
struct tm tstruct = *localtime(&now);
float f = tstruct.tm_hour + tstruct.tm_min / 60.0 + tstruct.tm_sec / 3600.0;
cout << f << endl; // prints 10.1025 at 10:06:09
关于c++ - 如何将时间转换为整数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25544160/