Home > Mobile >  Printing time_t in a vector struct member
Printing time_t in a vector struct member

Time:05-18

Sorry, I think this might be a silly question. While trying to use ctime to print a time_t inside a vector struct member, the compiler throws me this error argument of type "time_t" is incompatible with parameter of type "const tm *"

struct Trade_Record
{
    std::time_t PASP;
};

std::vector<Trade_Record> Trade_Records;


for (std::vector<Trade_Record>::iterator begin = Trade_Records.begin(); begin != Trade_Records.end(); begin  )
{
    std::cout << ctime(begin->PASP) << endl;
}

How could I print time_t inside a vector struct member? Thank youuu!!

CodePudding user response:

Quoting cppreference.com on the matter:

This function returns a pointer to static data and is not thread-safe. In addition, it modifies the static std::tm object which may be shared with std::gmtime and std::localtime. POSIX marks this function obsolete and recommends std::strftime instead.
The behavior may be undefined for the values of std::time_t that result in the string longer than 25 characters (e.g. year 10000)

You should use strftime instead:

#include <iostream>
#include <ctime>

int main() {
    std::time_t t = std::time(nullptr);
    char mbstr[100];
    
    if (std::strftime(mbstr, sizeof(mbstr), "%A %c", std::localtime(&t))) {
        std::cout << mbstr << '\n';
    }
}

Output:

Tuesday Tue May 17 07:51:34 2022

(See online)

CodePudding user response:

Try this:

    std::cout << ctime(&begin->PASP) << std::endl;
  •  Tags:  
  • c
  • Related