Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Buy a domain name - Register cheap domain names from $0.99 - Namecheap

Scalable Hosting That Grows With You

Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Semrush - keyword research tool

Boost your online presence with premium web hosting and servers

Disclosure: My content contains affiliate links.

39,851 questions

51,772 answers

573 users

How to create a list of random dates in C++

1 Answer

0 votes
#include <iostream>
#include <vector>
#include <ctime>

// Function to generate a random date
std::tm generateRandomDate(int startYear, int endYear) {
    std::tm date = {};
    
    date.tm_year = startYear + rand() % (endYear - startYear + 1) - 1900; // Year since 1900
    date.tm_mon = rand() % 12; // Month (0-11)
    date.tm_mday = rand() % 28 + 1; // Day (1-28 to avoid complications with different month lengths)
    
    return date;
}

// Function to print a date
void printDate(const std::tm& date) {
    std::cout << (date.tm_year + 1900) << "-" 
              << (date.tm_mon + 1) << "-" 
              << date.tm_mday << std::endl;
}

int main() {
    srand(time(0)); // Seed the random number generator

    int numberOfDates = 5; // Number of random dates to generate
    int startYear = 2000;
    int endYear = 2025;

    std::vector<std::tm> randomDates;

    for (int i = 0; i < numberOfDates; i++) {
        randomDates.push_back(generateRandomDate(startYear, endYear));
    }

    for (const auto& date : randomDates) {
        printDate(date);
    }
}

   
   
/*
run:
   
2012-1-3
2001-6-11
2018-9-2
2025-11-12
2023-1-23
   
*/

 



answered Apr 18, 2025 by avibootz
edited Apr 18, 2025 by avibootz
...