Search code examples
c++dateweekday

How to change the ouput from 1 to Monday?


I am using code from here: https://www.geeksforgeeks.org/find-day-of-the-week-for-a-given-date/. It finds the day of the week a date falls on. The output is a number corresponding to the day of the week but I would like it to say 'Monday' instead of '1'. How do I change it?

#include <iostream>

using namespace std;

int dayofweek(int d, int m, int y)
{
    static int t[] = { 0, 3, 2, 5, 0, 3,
                       5, 1, 4, 6, 2, 4 };
    y -= m < 3;
    return ( y + y / 4 - y / 100 +
             y / 400 + t[m - 1] + d) % 7;
}

int main()
{
    int day = dayofweek(03, 02, 2020);
    cout << day << endl;

    return 0;
}

Solution

  • Write a method that takes an integer input and returns a string.

    const char* day(int n) 
    {
        static const char* days[] = {
            "Monday", "Tuesday", …, "Sunday"
        }
        if (n >= 1 && n <= 7)
            return days[n-1];
        else
            return "Failday";
    }
    

    I assume here Sunday is 7; adjust accordingly if it's 0.

    You may prefer std::string to char*; I'll leave that detail to you.