-3

I want to accomplish task, that defines how many days is in specific Month, for this task i'm using date and time library to get current month, and then i want to check how many days in current month.

I'm getting this error:

no suitable constructor exists to convert from "char" to "std::basic_string, std::allocator>"

string daysInMonth(int month, string months);
time_t tt = system_clock::to_time_t(system_clock::now());
    struct tm * ptm = localtime(&tt);
    char buff[100];

    int days;
    string months[12] = {"January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"};
    int month =  ptm->tm_mon+1;


    switch (month)
    {
        case May: {
            days = 31;
            cout << daysInMonth(month, months);

    }
    }

string daysInMonth(int month, string months) {
    for (int i = 0; i < sizeof(months) / sizeof(months[0]); i++)
    {
        if (month == i)
        {
            return months[i - 1];

        }
    }
}
Retired Ninja
  • 4,785
  • 3
  • 25
  • 35
Viktor
  • 1,036
  • 1
  • 12
  • 25
  • @CoolGuy whoops, OP actually morphed his question since you commented, and that misled me. Please disregard my previous comment. – Quentin May 07 '17 at 16:57
  • 1
    Please don't morph your question into a new one. That invalidates the answers you've been given. If you have a different problem now, ask a different question. – Retired Ninja May 07 '17 at 17:11
  • You should read this: https://stackoverflow.com/questions/1975128/sizeof-an-array-in-the-c-programming-language and consider using a std::vector or a std::array which will allow you to do what you want. https://ideone.com/3Ym0hT – Retired Ninja May 07 '17 at 17:22

1 Answers1

5

when you declare the function daysInMonth, you tell the compiler that the months parameter is a single string, so it thinks that months[i - 1] will evaluate to a single character in a string.

In order to fix this, change the declaration of daysInMonth to string daysInMonth(int month, string months[12]).

beeselmane
  • 1,111
  • 8
  • 26
  • thanks this solved the problem but now its trows this: Exception thrown at 0x000D59FB in Basic_1.exe: 0xC0000005: Access violation reading location 0xCCCCCCE0. – Viktor May 07 '17 at 16:45
  • 1
    I'm going to guess your crash is in code that isn't in your question. Since this one is answered you should put together a short complete example that demonstrates the error and ask another question about it. – Retired Ninja May 07 '17 at 16:59
  • 1
    Well, this complete example works: https://ideone.com/58TePv Notice I simplified your daysInMonth function. Since we cannot compile your example as-is we certainly don't see all the code. – Retired Ninja May 07 '17 at 17:09