2015-05-10 69 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'; 
相關問題