Search code examples
c++datetimelocaleoverloading

Implementation of locale formatted time output


I am trying to implement in a program the code for printing locale time in C++ given in How to get current time and date in C++? .

I made some correction to adapt the code to my header but it still gives me an error "Method 'put' could not be resolved". I am novice so I could not find an answer. I am on Eclipse. I have set the scalability number of the editor to 50000. Also the file has another class between inclusions and code.

The code is this:

#ifndef LISTA_H_
#define LISTA_H_

#include "nodel.h"
#include "hntable.h"

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

using namespace std;

class timefmt
{
public:
    timefmt(std::string fmt)
        : format(fmt) { }

    friend ostream& operator <<(ostream &, timefmt const &);

private:
    string format;
};


std::ostream& operator <<(std::ostream& os, timefmt const& mt)
{
    std::ostream::sentry s(os);

    if (s)
    {
        time_t t = time(0);
        tm const* tm = localtime(&t);
        ostreambuf_iterator<char> out(os);

        use_facet<time_put<char>>(os.getloc())
            .put(out, os, os.fill(),
                 tm, &mt.format[0], &mt.format[0] + mt.format.size());
    }

    os.width(0);

    return os;
}

#endif /* LISTA_H_ */

Edit: If I include "locale" the error previously show is solved but: multiple definition of `operator<<(std::ostream&, timefmt const&)' . Any hints about this?


Solution

  • Just add #include <locale>, and your code compiles