How to change the string s to char * a []?

advertisements

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 ?


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.