4

I want to transform

string s="aaa,bbb,ccc"

into:

char * a[]={"aaa", "bbb", "ccc"}

Could you help me how to program for dealing with this process?

I will try to program like this:

string s="aaa,bbb,ccc";
char * a[];
char id[] = "";
strcpy(id, s.c_str());
const char * split = ",";
char * p;

    p = strtok(id, split);
    while (p != NULL) {
        int i = 0;
        printf("%s\n", p);
        a[i]=p;

        i++;
        p = strtok(NULL, split);
    }

where is my wrong? who can point out ?

Baren
  • 69
  • 1
  • 8
  • 2
    You can't, the dimensions of `a` need to be known at compile time. – juanchopanza Aug 26 '15 at 08:55
  • but i can't confirm the dimensions of s. maybe s ="aaa,bbb,ccc,ddd,..." so I hope slicing by "," – Baren Aug 26 '15 at 09:02
  • check Boost Tokenizer http://www.boost.org/doc/libs/1_58_0/libs/tokenizer/ – Hcorg Aug 26 '15 at 09:07
  • 1
    Can you describe what you are trying to accomplish with this? – Simon Kraemer Aug 26 '15 at 09:09
  • the string s come from config.ini ,i fopen the config.ini use string s transform into char *a[]={"","",""} for my function call it .my function is subdata(a) – Baren Aug 26 '15 at 09:14
  • Did you write this function `subdata`? Can you change it, or must you conform to an existing interface? Can you show us the declaration of `subdata`? – Useless Aug 26 '15 at 10:40
  • the subdata() is defined by third party ,i just reference it . subdata( char * ppInstrumentID[], int nCount ) – Baren Aug 26 '15 at 11:15

2 Answers2

2

I'm new to programming, but I've been doing the following:

#include "stdafx.h"
#include <stdio.h>
#include <iostream>


int _tmain(int argc, _TCHAR* argv[])
{       
    std::string s = "aaa,bbb,ccc";

    // dynamically allocate memory for the char
    char * a = new char [s.length()+1];

    // the string needs to be copied into a
    std::strcpy(a, s.c_str());

    std::cout << a;

    // cleanup
    delete [] a;

    return 0;
}

Edit: Just noticed you want the different parts of the string as elements of the char array, my answer doesn't do that.

ganrob
  • 39
  • 1
2

I suggest to use a std::vector<std::string> to store your results instead of char* [], it should be more useful.

So, try this one, purely C++ std library.

But if you surely need a char* [], I suggest that write a converter function, , like:

char** ToCharArrays(const std::vector<std::string>& strings)
{
    char** cs = new char* [strings.size()];
    for (int i = 0, l = strings.size(); i < l; ++i)
    {
        cs[i] = const_cast<char*>(strings[i].c_str());
    }
    return cs;
}

Use case is like this:

std::string input("aaa,bbb,ccc");
std::vector<std::string> strings = Split(input, ',');
char** asCharArrays = ToCharArrays(strings);
YourAPINeedsCharArrays(asCharArrays, strings.size());
delete[] asCharArrays;
Community
  • 1
  • 1
Marson Mao
  • 2,935
  • 6
  • 30
  • 45