5
votes

How to get text representation for Vector3f or other types in Eigen library. I see lot of examples that uses .format() which returns WithFormat class. This then can be used with cout. However I'm looking for way to get Vector3f as std:string in some human readable form. Exact formatting isn't too important so if Eigen has any default formatting then that works as well.

Note: I can certainly use stringstream to replace cout but I'm hopping there is more direct way to do this.

3

3 Answers

9
votes

The easiest solution I found out, not sure if optimal, is:

static std::string toString(const Eigen::MatrixXd& mat){
    std::stringstream ss;
    ss << mat;
    return ss.str();
}
2
votes

As far as I know, the stringstream method is the way to go. In fact, in the IO.h file (Eigen::internal::print_matrix) the developers use stringstreams to obtain the width of each entry.

1
votes

The approach I finally took is as follows:

static std::string toString(const Vector3d& vect)
{
    return stringf("[%f, %f, %f]", vect[0], vect[1], vect[2]);
}

static string stringf(const char* format, ...)
{
    va_list args;
    va_start(args, format);

    int size = _vscprintf(format, args) + 1;
    std::unique_ptr<char[]> buf(new char[size] ); 

    #ifndef _MSC_VER
        vsnprintf(buf.get(), size, format, args);
    #else
        vsnprintf_s(buf.get(), size, _TRUNCATE, format, args);
    #endif

    va_end(args);            

    return string(buf.get());
}