I have a function as
transTime()
{
time_t const now_c = time(NULL);
cout << put_time(localtime(&now_c), "%a %d %b %Y - %I:%M:%S%p");
}
I'm trying to save the value returned into a variable such that I can do something like
string myTime = put_time(localtime(&now_c), "%a %d %b %Y - %I:%M:%S%p");
I need to use the same instance of myTime for two different insertions.
Edit/Update:
After using stringstream,
string transTime()
{
stringstream transTime;
time_t const now_c = time(NULL);
transTime << put_time(localtime(&now_c), "%a %d %b %Y - %I:%M:%S%p");
string myTime = transTime.str();
//transTime >> myTime;
return myTime;
}
When I use call the function, I get Tue
alone, instead of the complete date and time.
Most likely has to do with getline, not sure how to implement that.
Any help ?
When you use a stringstream
to capture the localtime()
's output, you can store the string stored in stringstream
by using .str()
.
That is,
string myTime = transTime.str();
return myTime;
Firstly, you need to use the tm structure included in most if not all compiler standard libraries, then you can pass the data from the 'tm' object to a string:
string transTime()
{
time_t rawtime;
struct tm * timeContext;
string temp;
stringstream textStream;
time(&rawtime);
timeContext = localtime(&rawtime);
textStream << asctime(timeContext);
temp = textStream.str();
return temp;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With