2015-05-10 71 views
-1

我有一个C++应用程序,我正在开发中,我只需要检查当前日期是否在char数组中,具体格式为“2015-05-10”。我对PHP的C++非常陌生,它很容易做到,但我努力在C++中寻找一个好方法。随着脚本每天在cron作业上运行,这需要自动执行。所以这个过程是:C++ - 如何检查今天的日期是一个字符串?

If (today's date is in char array) { 
do this } 
else { 
do nothing 
} 

编辑:我明显无用的表达我的问题,对不起!

我的主要问题是:

  1. 如何获得当天的日期在一个不错的简单的字符串以这种格式 - 2015年5月10日

  2. 我如何再检查是否有字符数组我已经存储了(我知道包含其他文本中的日期)包含当天的日期(当我知道如何将它存储为字符串时)。

+0

有['标准:: regex'(http://en.cppreference.com/w/cpp/regex/basic_regex)来实现这样的格式检查。 –

+0

“检查当天的日期是否在字符数组中”肯定你会知道,因为你从哪里得到日期 - 而且返回类型不会改变。 – cmannett85

+0

@ cmannett85 char数组存储来自另一个服务器的响应(响应包含其他文本以及日期),并且在24小时内的相同点将从包含旧日期变为当前日期。因此,当我获取新的回复时,我需要检查它是否包含今天的日期,并据此采取行动。 – Tim

回答

0

如果我理解正确,首先要将当前日期转换为yyyy-mm-dd格式,然后在另一个字符串中搜索字符串。

对于第一个问题,您可以参考How to get current time and date in C++?,其中有多个解决方案。 对于问题的第二部分,如果你使用的字符串,你应该使用找到http://www.cplusplus.com/reference/string/string/find/)方法,如果您使用的字符数组,你可以使用C 的strstr(http://www.cplusplus.com/reference/cstring/strstr/)方法。 这里是我的尝试:

 #include <iostream> 
     #include <string> 
     #include <cstdio> 
     #include <ctime> 
     #include <cstring> 

    time_t  now = time(0); 
    struct tm tstruct; 
    char  buf[100]; 
    tstruct = *localtime(&now); 
    strftime(buf, sizeof(buf), "%Y-%m-%d", &tstruct); 

    //char arrays used 
    char ch_array[] = "This is the received string 2015-05-10 from server"; 
    char * pch; 
    pch = strstr(ch_array, buf); 
    if (pch != nullptr) 
     std::cout << "Found"; 

    //string used 
    std::string str("This is the received string 2015-05-10 from server"); 
    std::size_t found = str.find(buf); 
    if (found != std::string::npos) 
     std::cout << "date found at: " << found << '\n'; 
相关问题