Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I convert const char* to string and then back to char*?

I'm just starting c++ and am having difficulty understanding const char*. I'm trying to convert the input in the method to string, and then change the strings to add hyphens where I want and ultimately take that string and convert it back to char* to return. So far when I try this it gives me a bus error 10.

char* getHyphen(const char* input){
    string vowels [12] = {"A","E","I","O","U","Y","a","e","i","o","u","y"};

    //convert char* to string
    string a;
    int i = 0;
    while(input != '\0'){
        a += input[i];
        input++;
        i++;
    }

    //convert a string to char*

    return NULL;
}
like image 602
Arya Atighehchian Avatar asked Sep 22 '15 20:09

Arya Atighehchian


2 Answers

First of all, you don't need all of that code to construct a std::string from the input. You can just use:

string a(input);

As far as returning a new char*, you can use:

return strdup(a.c_str());  // strdup is a non-standard function but it
                           // can be easily implemented if necessary.

Make sure to deallocate the returned value.

It will be better to just return a std::string so the users of your function don't have to worry about memory allocation/deallocation.

std::string getHyphen(const char* input){
like image 200
R Sahu Avatar answered Oct 21 '22 00:10

R Sahu


A: The std::string class has a constructor that takes a char const*, so you simply create an instance to do your conversion.

B: Instances of std::string have a c_str() member function that returns a char const* that you can use to convert back to char const*.

auto my_cstr = "Hello";        // A
std::string s(my_cstr);        // A
// ... modify 's' ...
auto back_to_cstr = s.c_str(); // B
like image 39
bku_drytt Avatar answered Oct 21 '22 00:10

bku_drytt