28

I am trying to pass a value from C++ to TCL. As I cannot pass pointers without the use of some complicated modules, I was thinking of converting a vector to a char array and then passing this as a null terminated string (which is relatively easy).

I have a vector as follows:

12, 32, 42, 84  

which I want to convert into something like:

"12 32 42 48"

The approach I am thinking of is to use an iterator to iterate through the vector and then convert each integer into its string representation and then add it into a char array (which is dynamically created initially by passing the size of the vector). Is this the right way or is there a function that already does this?

fbrereto
  • 35,429
  • 19
  • 126
  • 178
Legend
  • 113,822
  • 119
  • 272
  • 400

4 Answers4

64

What about:

std::stringstream result;
std::copy(my_vector.begin(), my_vector.end(), std::ostream_iterator<int>(result, " "));

Then you can pass the pointer from result.str().c_str()

fbrereto
  • 35,429
  • 19
  • 126
  • 178
8

You can use copy in conjunction with a stringstream object and the ostream_iterator adaptor:

#include <iostream>

#include <sstream>
#include <string>
#include <vector>
#include <algorithm>
using namespace std;

int main()
{
    vector<int> v;
    v.push_back(12);
    v.push_back(32);
    v.push_back(42);
    v.push_back(84);

    stringstream ss;
    copy( v.begin(), v.end(), ostream_iterator<int>(ss, " "));
    string s = ss.str();
    s = s.substr(0, s.length()-1);  // get rid of the trailing space

cout << "'" << s << "'";

    return 0;
}

Output is:

'12 32 42 84'

John Dibling
  • 99,718
  • 31
  • 186
  • 324
4

I'd use a stringstream to build the string. Something like:

std::vector<int>::const_iterator it;
std::stringstream s;
for( it = vec.begin(); it != vec.end(); ++it )
{
    if( it != vec.begin() )
        s << " ";

    s << *it;
}

// Now use s.str().c_str() to get the null-terminated char pointer.
Jon Benedicto
  • 10,492
  • 3
  • 28
  • 30
2

You got it right, but you can use std::ostringstream to create your char array.

#include <sstream>

std::ostringstream StringRepresentation;
for ( vector<int>::iterator it = MyVector.begin(); it != MyVector.end(); it++ ) {
    StringRepresentation << *it << " ";
}

const char * CharArray = StringRepresentation.str().c_str();

In this case, CharArray is only for reading. If you want to modify the values, you will have to copy it. You can simplify this by using Boost.Foreach.

Björn Pollex
  • 75,346
  • 28
  • 201
  • 283