C++ c++;如果当前时间=给定时间

C++ c++;如果当前时间=给定时间,c++,C++,我需要帮助我有一个简单的程序,但它不会工作 这是我的密码 我想检查当前系统时间是否等于给定的时间,然后做一些事情 #include "stdafx.h" #include <iostream> #include <string> #include <stdio.h> #include <time.h> #pragma warning(disable : 4996) const std::string currentDat

我需要帮助我有一个简单的程序,但它不会工作 这是我的密码 我想检查当前系统时间是否等于给定的时间,然后做一些事情


#include "stdafx.h"
#include <iostream>
#include <string>
#include <stdio.h>
#include <time.h>
#pragma warning(disable : 4996) 


const std::string currentDateTime() {
    time_t     now = time(0);
    struct tm  tstruct;
    char       buf[80];
    tstruct = *localtime(&now);
    strftime(buf, sizeof(buf), "%Y-%m-%d.%X", &tstruct);
    
    
    return buf;

}

int main() {
    while (true)
    {
        currentDateTime();
        char * currtimetochar = strcpy(new char[currentDateTime().length() + 1], currentDateTime().c_str());
        //std::cout << idokes << std::endl;
        if (currtimetochar == "2020-08-31.19:29:59")//given time date for example {
        std::cout << "success!" << std::endl;
         // do something more 
        }
    }

    getchar();  
}

#包括“stdafx.h”
#包括
#包括
#包括
#包括
#杂注警告(禁用:4996)
常量std::字符串currentDateTime(){
现在时间=时间(0);
struct-tm-tstruct;
char-buf[80];
tstruct=*本地时间(&now);
strftime(buf,sizeof(buf),%Y-%m-%d.%X“,&t结构);
返回buf;
}
int main(){
while(true)
{
currentDateTime();
char*currtimetochar=strcpy(新字符[currentDateTime().length()+1],currentDateTime().c_str());

//std::cout更好的方法是将给定的时间字符串编码为LOCALTIME或SYSTEMTIME,并对其进行比较,而不是比较格式会在不同地区发生变化的字符串。SYSTEMTIME更适合于“绝对时间比较”(以UTC为单位)尽管使用LOCALTIME可能足以满足您的需要。

在“成功”之后有一个额外的结束括号。您应该删除它。您正在泄漏一个完整的
char[]
您的紧密潜在无限循环的每个迭代。您正在将
currtimetochar
进行比较“2020-08-31.19:29:59”
这将始终为false,因为它将数组的地址与C字符串“2020-08-31.19:29:59”的文本地址进行比较
会做你想做的事。避免
新的
这在现代代码中是不需要的。相反,请参阅
std::make_unique
。哦,就是这么简单,非常感谢你的帮助!!!