0

If I have an integer vector (std::vector) is there an easy way to convert everything in that vector to a char array(char[]) so (1,2,3) -> ('1','2','3') This is what I have tried, but it doesn't work:

std::vector<int> v;

for(int i = 1; i  < 10; i++){
    v.push_back(i);
}

char *a = &v[0];
3
  • I question why you need to do this. Also why not convert it to std::string? May 27, 2016 at 13:32
  • You can use itoa to go from int to char like you want. std::transform (cplusplus.com/reference/algorithm/transform) will let you do it on a container.
    – user2201041
    May 27, 2016 at 13:34
  • What result do you expect for integers larger than 9, or smaller than 0? May 27, 2016 at 13:38

5 Answers 5

5

std::transform is the right tool for the job :

std::vector<int> iv {1, 2, 3, 4, 5, 6};
char ca[10] {};

using std::begin;
using std::end;
std::transform(begin(iv), end(iv), begin(ca), [](int i) { return '0' + i; });

If you don't need ca to be a C-style array, I'd recommend using std::array or std::vector instead. The latter needs std::back_inserter(ca) in place of begin(ca).

3
  • Is there a way to do this so that the char array is dynamically allocated? so it can have variable size May 27, 2016 at 14:08
  • @AllenHuang You could allocate it with new and pass the pointer itself to std::transform, but the better idea is to use std::vector.
    – Quentin
    May 27, 2016 at 14:15
  • that worked thanks and I am using a char array because I'm using this with zLib May 27, 2016 at 14:17
2

It can be as simple as this

std::vector<int> v { 1, 2, 3 };
std::vector<char> c;
for( int i : v ) c.push_back( '0' + i );

to realize why your way does not work you need to learn how integers and symbls represented on your platform.

0

Why not store it in char vector initially?

std::vector<char> v;
for(int i = 1; i  < 10; i++){
    v.push_back(i + '0');
}

Trick from: https://stackoverflow.com/a/2279401/47351

0

You can use std::transform with std::back_inserter, maybe something like this:

#include <iostream>
#include <vector>
#include <algorithm>

int main()
{
    std::vector<int> vI{0,1,2,3,4,5,6,7,8,9};
    std::vector<char> vC;
    std::transform(vI.begin(), vI.end(), std::back_inserter(vC), [](const int &i){ return '0'+i; });

    for(const auto &i: vC)
    {
        std::cout << i << std::endl;
    }
    return 0;
}
0

If you've already got the numbers in a vector then you can use std::transform and a back_inserter:

std::vector<int> v;

std::vector<char> c;
std::transform(v.begin(), v.end(), std::back_inserter(c), [](int i){return '0' + i;});

However, why not just say:

std::vector<char> v;

for(char i = '0'; i < '9'; i++)
{
    v.push_back(i);
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.