Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get put_time into a variable

Tags:

c++

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 ?

like image 992
hello Avatar asked Mar 11 '15 02:03

hello


2 Answers

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;
like image 127
shauryachats Avatar answered Oct 20 '22 09:10

shauryachats


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;    
    }
like image 1
edition Avatar answered Oct 20 '22 09:10

edition