Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ convert char to const char*

Basically i just want to loop through a string of characters pull each one out and each one has to be of type const char* so i can pass it to a function. heres a example. Thanks for your help.

    string thestring = "abc123";
    const char* theval;
    string result;

    for(i = 0; i < thestring.length(); i++){
        theval = thestring[i]; //somehow convert this must be type const char*
        result = func(theval);
    }
like image 719
user1054513 Avatar asked Dec 08 '11 20:12

user1054513


3 Answers

You can take the address of that element:

theval = &thestring[i];
like image 82
Luchian Grigore Avatar answered Oct 04 '22 07:10

Luchian Grigore


string sym(1, thestring[i]);
theval = sym.c_str();

It gives a null-terminated const char* for every character.

like image 23
dimitri Avatar answered Oct 04 '22 08:10

dimitri


Usually a const char * is pointing to a full null-terminated string, not a single character, so I question if this is really what you want to do.

If it's really what you want, the answer is easy:

theval = &thestring[i];

If the function is really expecting a string but you want to pass it a string of a single character, a slightly different approach is called for:

char theval[2] = {0};
theval[0] = thestring[i];
result = func(theval);
like image 6
Mark Ransom Avatar answered Oct 04 '22 07:10

Mark Ransom