Setting a specific date in c++

483 Views Asked by At

i want to set a date, so that if the current date exceed the date set, the function will not run. For example after a certain date user are not able to vote anymore.

#include<iostream>
#include<iomanip>
#include<string>
#include<stdlib.h>
#include<time.h>
#define enddate "2022-12-30"
using namespace std;

int nominationMenu() {
    time_t ct = time(0);
    string currenttime= ctime(&ct);
    string candid_mykad, candidID;
    string program;
    int candidstudyyear;
    if (currenttime<enddate) {
        cout << setw(49) << setfill('-') << "-" << endl;
        cout << setw(50) << setfill(' ') << left << "\n                NOMINATION SESSION" << endl;
        cout << setw(50) << setfill('-') << "\n-" << endl;
        cout << "PLease keep in mind that the voting session will only begin after the 26th of December." << endl;
        cout << "One candidate per student.\n" << endl;
        system("pause");
        cout << "Please enter candidate's information:" << endl;
        cout << "\nMyKad (without dashes '-') \t:" << endl;
        cin >> candid_mykad;
        cout << "Student ID (full alphanumeric e.g. 22WMR12345) \t: " << endl;
        cin >> candidID;
        cout << "Program \t:" << endl;
        cin.ignore(1000, '\n');
        getline(cin, program);
        cout << "Year of study \t:" << endl;
        cin >> candidstudyyear;

        cout << "\nYou have nominated a candidate." << endl;
    }
    else
        cout << "Nomination session has ended. Please proceed to the voting session." << endl;

    return 0;
}

i tried setting a constant but that did not work. it just go straight to the else statement.

1

There are 1 best solutions below

6
Jerry Coffin On

Rather than converting the dates to strings, and comparing the strings, I'd convert all the dates to time_ts, and compare them.

struct tm enddate {
    .tm_mday = 13, // one based
    .tm_mon  = 11, // zero based
    .tm_year = 122 // year - 1900
};

int nominationMenu() {
    time_t ct = time(0);

    time_t et = mktime(&enddate); // convert to a time_t

    string candid_mykad, candidID;
    string program;
    int candidstudyyear;
    if (ct < et) {                // compare the time_t's

    // ...

As it stands, this theoretically might not be entirely portable. C++ designated initializers are required to be in the order the members are defined. This works with the major compilers (MS, gcc, clang) but in theory, it would probably be allowed for somebody to rearrange the fields of a struct tm, so that it wouldn't.