0

I was wondering if there is a way to convert an Armadillo vector to a std string. For example if I have this vector:

arma::vec myvec("1 2 3"); //create a vector of length 3 

How can I produce:

std::string mystring("1 2 3");

from it?

Cinnamon
  • 43
  • 4

2 Answers2

1

Use a combination of ostringstream, .raw_print(), .st(), .substr(), as below.

// vec is a column vector, or use rowvec to declare a row vector
arma::vec myvec("1.2 2.3 3.4");  

std::ostringstream ss;

// .st() to transpose column vector into row vector
myvec.st().raw_print(ss);  

// get string version of vector with an end-of-line character at end
std::string s1 = ss.str();

// remove the end-of-line character at end
std::string s2 = s1.substr(0, (s1.size() > 0) ? (s1.size()-1) : 0);

If you want to change the formatting, look into fmtflags:

std::ostringstream ss;
ss.precision(11);
ss.setf(std::ios::fixed);
hbrerkere
  • 1,561
  • 8
  • 12
0

This should work:

std::ostringstream s;
s << myvec;
std::string mystring = s.str();
molbdnilo
  • 64,751
  • 3
  • 43
  • 82
  • Fabulous, thanks! Do you know why when I print it, it shows up as a column vector rather than characters in a row? How can I get it to be of the latter form? – Cinnamon Aug 26 '20 at 09:31
  • To clarify, if I do for(int i=0;i – Cinnamon Aug 26 '20 at 09:36
  • Oops. That'It shows up as a column vector because `vec` is a column vector. You could always transpose it, I guess. – molbdnilo Aug 26 '20 at 09:40