I wrote a function which returns the current date. Inside the function, I “cout” the result and it work but when I “cout” the function, it does not work. I got garbage.
const char* engineCS::getDate() const
{
time_t t = time(0);
struct tm *now = localtime(&t);
char buf[20];
strftime(buf, sizeof(buf), "%Y-%m-%d %X", now);
cout << buf << endl;
return buf;
}
Exemple :
Inside : 2012-02-02 00:00:00
Outside : ?????fv
What is wrong?
Similar problem : Functions and return const char*
THX
Edit:
What is wrong now? Sorry I’ve done too much VB.NET…
const char* engineCS::getDate() const
{
time_t t = time(0);
struct tm *now = localtime(&t);
char *buf;
buf = new char[20];
strftime(buf, sizeof(buf), "%Y-%m-%d %X", now);
cout << buf << endl;
return buf;
}
Change your function to return
std::string, and everything will be fine. You won’t need to make any further changes apart from the return type. If the consumer needs a rawchar const *, call thec_str()member function on the resulting string.