Search code examples
eigeneigen3

How to convert Eigen library's Matrix or Vector types to string?


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.


Solution

  • 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());
    }