简体   繁体   English

如何将 const char* 转换为字符串,然后再转换回 char*?

[英]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* .我刚刚开始 c++ 并且很难理解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.我正在尝试将方法中的输入转换为string ,然后更改字符串以在我想要的位置添加连字符并最终获取该字符串并将其转换回char*以返回。 So far when I try this it gives me a bus error 10.到目前为止,当我尝试这个时,它给了我一个总线错误 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;
}

A: The std::string class has a constructor that takes a char const* , so you simply create an instance to do your conversion. 答: std::string类有一个构造函数,它接受一个char const* ,所以你只需要创建一个实例来进行转换。

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* . 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

First of all, you don't need all of that code to construct a std::string from the input. 首先,您不需要所有代码来从输入构造std::string You can just use: 你可以使用:

string a(input);

As far as returning a new char* , you can use: 至于返回一个新的char* ,您可以使用:

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这样你的函数用户就不必担心内存分配/释放。

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

Don't use char* . 不要使用char* Use std::string , like all other here are telling you. 像这里的所有其他人一样告诉你使用std::string This will eliminate all such problems. 这将消除所有这些问题。

However, for the sake of completeness and because you want to understand the background, let's analyse what is going on. 但是,为了完整起见并且因为您想了解背景,让我们分析一下发生了什么。


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

You probably mean: 你可能意味着:

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

Your code compares the input pointer itself to \\0 , ie it checks for a null-pointer, which is due to the unfortunate automatic conversion from a \\0 char . 您的代码将input指针本身与\\0进行比较,即它检查空指针,这是由于来自\\0 char的不幸自动转换造成的。 If you tried to compare with, say, 'x' or 'a' , then you would get a compilation error instead of runtime crashes. 如果您尝试与'x''a' ,那么您将收到编译错误而不是运行时崩溃。

You want to dereference the pointer via *input to get to the char pointed to. 您希望通过*input 取消引用指针以获取指向的char

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

This will also not work. 这也行不通。 You increment the input pointer, yet with [i] you advance even further . 你递增input指针,但是[i]进一步前进。 For example, if input has been incremented three times, then input[3] will be the 7th character of the original array passed into the function, not the 4th one. 例如,如果input增加了三次,则input[3]将是传递给函数的原始数组的第7个字符,而不是第4个字符。 This eventually results in undefined behaviour when you leave the bounds of the array. 当您离开数组的边界时,这最终会导致未定义的行为。 Undefined behaviour can also be the "bus error 10" you mention. 未定义的行为也可能是您提到的“总线错误10”

Replace with: 用。。。来代替:

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

(Actually, now that i is not used any longer, you can remove it altogether.) (实际上,既然i已经不再使用了,你可以完全删除它。)


And let me repeat it once again: Do not use char* . 让我再说一遍:不要使用char* Use std::string . 使用std::string

Change your function declaration from 从中更改函数声明

char* getHyphen(const char* input)

to

auto hyphenated( string const& input )
    -> string

and avoid all the problems of conversion to char const* and back. 并避免转换为char const*和返回的所有问题。

That said, you can construct a std::string from a char_const* as follows: 也就是说,您可以从char_const*构造一个std::string ,如下所示:

string( "Blah" )

and you get back a temporary char const* by using the c_str method. 然后使用c_str方法返回临时char const*

Do note that the result of c_str is only valid as long as the original string instance exists and is not modified. 请注意,只要原始string实例存在且未被修改, c_str的结果才有效。 For example, applying c_str to a local string and returning that result, yields Undefined Behavior and is not a good idea. 例如,将c_str应用于本地string并返回该结果,会产生未定义的行为,这不是一个好主意。 If you absolutely must return a char* or char const* , allocate an array with new and copy the string data over with strcpy , like this: return strcpy( new char[s.length()+1], s.c_str() ) , where the +1 is to accomodate a terminating zero-byte. 如果绝对必须返回char*char const* ,则使用new分配一个数组并使用strcpy复制字符串数据,如下所示: return strcpy( new char[s.length()+1], s.c_str() ) ,其中+1是为了容纳终止的零字节。

Exchange functions of data types in C/C++ convenience. C/C++ 方便的数据类型交换函数。 In this repo there are convenience functions of all c++ data types and I wrote them all as in python.在这个 repo 中有所有 c++ 数据类型的便利函数,我把它们都写在 python 中。

Use This Repo:使用这个回购:

https://github.com/azizovrafael/Simple-CPlusPlus https://github.com/azizovrafael/Simple-CPlusPlus

Example:例子:

...

int main(){
   int n = INT(INPUT("Write Some Text For Console Ex. (Enter: )"));
   string str = STR(n);
 
   return 0;
}

...

#simplecplusplus #simplecplusplus

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM