如何从函数返回字符串

Vik*_*tor -3 c++

我想完成任务,定义特定月份的天数,对于此任务,我使用日期和时间库来获取当前月份,然后我想检查当月的天数.

我收到这个错误:

没有合适的构造函数可以从"char"转换为"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];

        }
    }
}
Run Code Online (Sandbox Code Playgroud)

bee*_*ane 5

当您声明该函数时daysInMonth,您告诉编译器该months参数是单个字符串,因此它认为months[i - 1]将评估为字符串中的单个字符.

为了解决这个问题,请将声明更改daysInMonth string daysInMonth(int month, string months[12]).