如何从函数返回字符串
问题描述:
我想完成任务,该任务定义特定月份中有多少天,对于此任务,我使用日期和时间库获取当前月份,然后我想检查多少天在当前月份。如何从函数返回字符串
我得到这个错误:
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];
}
}
}
答
当你声明的功能daysInMonth
,你告诉编译器,这个months
参数是一个字符串,因此它认为months[i - 1]
将评估到字符串中的单个字符。
为了解决这个问题,请将daysInMonth
的声明更改为 string daysInMonth(int month, string months[12])
。
@CoolGuy哎呀,OP实际上是在你评论之后变形了他的问题,并且误导了我。请忽略我以前的评论。 – Quentin
请不要将您的问题转化为新问题。这使得你得到的答案无效。如果您现在有其他问题,请提出其他问题。 –
你应该阅读这个:https://stackoverflow.com/questions/1975128/sizeof-an-array-in-the-c-programming-language并考虑使用一个std :: vector或一个std ::数组,这将允许你做你想做的事。 https://ideone.com/3Ym0hT –