Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/sockets/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ 类或函数中的Strftime问题_C++_Strftime_Ctime - Fatal编程技术网

C++ 类或函数中的Strftime问题

C++ 类或函数中的Strftime问题,c++,strftime,ctime,C++,Strftime,Ctime,我在main上写了这段代码,它工作得很好,但当我尝试将它放在函数或类方法中时,它不工作,为什么? 此外,当我调试这段代码时,似乎没有编译time\t和struct tmp const char* getFormat() { time_t rawtime; struct tm * timeinfo; char buffer[80]; time(&rawtime); timeinfo = localtim

我在main上写了这段代码,它工作得很好,但当我尝试将它放在函数或类方法中时,它不工作,为什么? 此外,当我调试这段代码时,似乎没有编译time\t和struct tmp

const char*  getFormat()  { 
        time_t rawtime;
        struct tm * timeinfo;
        char buffer[80];

        time(&rawtime);
        timeinfo = localtime(&rawtime);

        strftime(buffer, sizeof(buffer), "%d.%m.%Y H%:%i", timeinfo);
        return buffer;
}

好吧,总结一下其他评论者所说的话(编辑:并正确地完成这项工作),这段代码运行良好:

#include <time.h>
#include <string>
#include <iostream>

std::string getFormat ()
{ 
    time_t rawtime;
    time(&rawtime);
    struct tm *timeinfo = localtime(&rawtime);
    char buffer [80];
    strftime(buffer, sizeof (buffer), "%d.%m.%Y %H:%I", timeinfo);
    return std::string (buffer);
}

int main ()
{
    std::string s = getFormat ();
    std::cout << s << "\n";
}

您可能希望使用
std::put\u time
而不是使用
strftime
。它采用相同的格式字符串,因此写出当前时间类似于:

time_t rawtime = std::time(nullptr);
tm *timeinfo = std::localtime(&rawtime);

std::cout << std::put_time(timeinfo, "%d.%m.%Y %H:%I") << "\n";
time\u t rawtime=std::time(nullptr);
tm*timeinfo=std::localtime(&rawtime);

如果此代码本身工作正常,那么导致问题的函数或类在哪里?如果没有完整的上下文,我们无法帮助您。@Yucel_K函数中的此代码不起作用,但当您在main上提取代码时,是workDon't post code起作用,post code不起作用。您返回一个指向局部变量
buffer
的指针<代码>缓冲区
在函数退出后立即变为无效,因此不能在调用函数中使用它。相反,在调用函数中考虑声明缓冲区并将其传递到 GETFrase ReCAP:返回指向调用方可以使用时的范围内的局部变量的指针。两个输入错误:
H%
->
%H
%i
->
%i
修复这些错误,您的函数应该可以工作。
time_t rawtime = std::time(nullptr);
tm *timeinfo = std::localtime(&rawtime);

std::cout << std::put_time(timeinfo, "%d.%m.%Y %H:%I") << "\n";