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

I am just starting out C ++ and can hardly understand const char*. I am trying to convert the input to a method in string, and then change the lines to add hyphens where I want, and end up taking that line and putting it back in char*to return. While I'm trying to do this, it gives me a 10 bus error.

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 string to char*

    return NULL;
}
+4
source share
4 answers

A: The class std::stringhas a constructor that accepts char const*, so you just create an instance to convert.

B: std::string - c_str(), char const*, char const*.

auto my_cstr = "Hello";        // A
std::string s(my_cstr);        // A
// ... modify 's' ...
auto back_to_cstr = s.c_str(); // B
+9

, std::string . :

string a(input);

char*, :

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

.

std::string, / .

std::string getHyphen(const char* input){
+1

char* getHyphen(const char* input)

auto hyphenated( string const& input )
    -> string

char const* .

, std::string char_const* :

string( "Blah" )

char const* c_str.

, c_str , string . , c_str string , Undefined . char* char const*, new strcpy, : return strcpy( new char[s.length()+1], s.c_str() ), +1 -.

0

char*. std::string, . .

, , , , .


while(input != '\0'){

, :

while(*input != '\0') {

input \0, .. , \0 char. , , 'x' 'a', .

*input, char, .

a += input[i];
input++;
i++;

. input, [i] . , input , input[3] 7- , , . undefined, . undefined " 10".

:

a += *input;
input++;
i++;

(In fact, now that it is ino longer in use, you can delete it altogether.)


And let me repeat again: Do not use char*. Use std::string.

0
source

Source: https://habr.com/ru/post/1608579/


All Articles