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;
}
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){
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With