我剛開始學習C++。 在瀏覽本網站上的代碼時,我遇到了驗證用戶輸入日期的代碼。但問題是它可能需要甚至將來的值,因此需要調整此邏輯以便接受DOB。因此我決定使用「time()」函數獲取當前時間,然後將其與輸入的日期進行比較。首先,我加入了兩行代碼(這是在下面的代碼註釋的那些),這是使用C++驗證出生日期
time(&tNow);
和
const struct tm *now = localtime(&tNow);
這裏是我的代碼:
#include <iostream>
#include <sstream>
#include <ctime>
using namespace std;
// function expects the string in format dd/mm/yyyy:
bool extractDate(const std::string& s, int& d, int& m, int& y){
std::istringstream is(s);
char delimiter;
if (is >> d >> delimiter >> m >> delimiter >> y) {
struct tm t = {0};
t.tm_mday = d;
t.tm_mon = m - 1;
t.tm_year = y - 1900;
t.tm_isdst = -1;
// normalize:
time_t when = mktime(&t);
time_t tNow;
// time(&tNow);
const struct tm *norm = localtime(&when);
// const struct tm *now = localtime(&tNow); /* when I uncomment this line the code
// does not accept future date */
// validate (is the normalized date still the same?):
return (norm->tm_mday == d &&
norm->tm_mon == m - 1 &&
norm->tm_year == y - 1900);
}
return false;
}
int main() {
std::string s("11/01/2015");
int d,m,y;
if (extractDate(s, d, m, y))
std::cout << "date "
<< d << "/" << m << "/" << y
<< " is valid" << std::endl;
else
std::cout << "date is invalid" << std::endl;
}
當我取消對const struct tm *now = localtime(&tNow);
的註釋時,代碼會爲任何未來的日期值提供正確的輸出作爲「無效日期」...但爲什麼會發生這種情況。我得到正確的輸出,但我想知道原因。
聽起來像你一直在某個地方擊中未定義的行爲,我只是不能真正發現在哪裏。編譯時是否收到任何警告? –
我正在使用在線編譯器(http://www.tutorialspoint.com/compile_cpp_online.php)來編譯這段代碼,它沒有給出任何錯誤,它工作正常 – Priyanka
不,它沒有顯示任何警告。 – Priyanka