You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

C++中如何验证日期格式为dd/mm/yyyy的正确性?

Hey there! Let's fix that date format validation gap in your code. Right now, your checkFormat function tries to adjust non-standard inputs but has critical logic flaws (like attempting to parse slashes as integers, which will crash your program), and you're not explicitly verifying if the input matches the required DD/MM/YYYY structure before validating date values. Here's how to address this properly:

1. Add Strict Format Validation with Regular Expressions

The most reliable way to check if an input follows the DD/MM/YYYY pattern is using a regular expression. C++11 and later support regex via the <regex> header. Add this function to your Validation class:

#include <regex>

bool Validation::isValidDateFormat(const std::string& input) {
    // Regex pattern: exactly 2 digits, slash, 2 digits, slash, 4 digits
    std::regex datePattern(R"(^\d{2}/\d{2}/\d{4}$)");
    return std::regex_match(input, datePattern);
}

This will return true only for inputs like 06/07/2008, and false for non-compliant formats such as 6/7/2008, 6/07/2008, or any other structure that doesn't match.

2. Adjust Your Input Validation Flow

Modify your date input loop to first check the format, then validate the date's numerical validity:

bool valid_date = false;
do {
    cout << "Enter your date of joining(DD/MM/YYYY): ";
    cin >> input;

    // First verify the format is correct
    if (!validate.isValidDateFormat(input)) {
        cout << "Invalid date format! Please enter the date in DD/MM/YYYY format (e.g., 06/07/2008)." << endl;
        continue; // Skip to next iteration to re-prompt the user
    }

    // Now validate the actual date values (year, month, day logic)
    valid_date = validate.valDate(input);
    if (valid_date) {
        person.SetDateJoined(input);
    } else {
        cout << "Invalid Date! Please re-enter date of joining!" << endl;
    }

} while(!valid_date);

3. Fix Existing Logic Flaws in Helper Functions

Your current Prepend_function has a logical error (the condition n < 10 && n < 0 will never be true) and is designed to return an integer—leading zeros can't be preserved in integers (since 06 as an integer is just 6). If you ever want to auto-correct single-digit days/months instead of rejecting them, rewrite it to return a string:

std::string Validation::prependZero(int n) {
    if (n >= 0 && n < 10) {
        return "0" + std::to_string(n);
    }
    return std::to_string(n);
}

Your original checkFormat function is unsafe (it tries to parse slashes as integers, which will throw exceptions). If you want to support auto-formatting, you'd need to first split the input by slashes, validate each part's length, then build the properly formatted string—but based on your requirement to reject non-compliant formats, this step might not be necessary.

4. Optional: Add Safety to valDate

Your valDate function is mostly solid, but you can add a try-catch block to handle unexpected conversion failures (though with the regex check first, this is less critical):

bool Validation::valDate(std::string input) {
    try {
        int Y = std::stoi(input.substr(6));
        int M = std::stoi(input.substr(3, 2));
        int D = std::stoi(input.substr(0, 2));

        // Rest of your existing validation logic here...
    } catch (const std::invalid_argument& e) {
        return false;
    } catch (const std::out_of_range& e) {
        return false;
    }
    return false;
}

With these changes, your program will properly reject inputs that don't match the DD/MM/YYYY format, give clear feedback to the user, and still validate the actual date values once the format is correct.

内容的提问来源于stack exchange,提问作者Adarsh Patel

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.20 10:29:57