如何从函数返回字符串

问题描述:

我想完成任务,该任务定义特定月份中有多少天,对于此任务,我使用日期和时间库获取当前月份,然后我想检查多少天在当前月份。如何从函数返回字符串

我得到这个错误:

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]; 

     } 
    } 
} 
+0

@CoolGuy哎呀,OP实际上是在你评论之后变形了他的问题,并且误导了我。请忽略我以前的评论。 – Quentin

+1

请不要将您的问题转化为新问题。这使得你得到的答案无效。如果您现在有其他问题,请提出其他问题。 –

+0

你应该阅读这个:https://stackoverflow.com/questions/1975128/sizeof-an-array-in-the-c-programming-language并考虑使用一个std :: vector或一个std ::数组,这将允许你做你想做的事。 https://ideone.com/3Ym0hT –

当你声明的功能daysInMonth,你告诉编译器,这个months参数是一个字符串,因此它认为months[i - 1]将评估到字符串中的单个字符。

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

+0

谢谢这解决了这个问题,但现在它的结果如下:在Basic_1.exe 0x000D59FB引发的异常:0xC0000005:访问冲突读取位置0xCCCCCCE0。 – Viktor

+1

我要猜测你的崩溃是在代码中,而不是你的问题。既然这个问题已经得到解答,你应该整理一个简短的完整例子来证明错误并提出另一个问题。 –

+0

我没有更多的代码,除了枚举类型 – Viktor