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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/32726444/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-28 14:12:01  来源:igfitidea点击:

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

c++stringcharconst

提问by Arya Atighehchian

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.

我刚刚开始使用 C++ 并且很难理解const char*。我正在尝试将方法中的输入转换为string,然后更改字符串以在我想要的位置添加连字符并最终获取该字符串并将其转换回char*以返回。到目前为止,当我尝试这个时,它给了我一个总线错误 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 != '
auto my_cstr = "Hello";        // A
std::string s(my_cstr);        // A
// ... modify 's' ...
auto back_to_cstr = s.c_str(); // B
'){ a += input[i]; input++; i++; } //convert a string to char* return NULL; }

回答by bku_drytt

A: The std::stringclass 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::stringhave 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*.

string a(input);

回答by R Sahu

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

首先,您不需要所有这些代码来std::string从输入构造 a 。你可以只使用:

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

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

至于返回一个 new char*,您可以使用:

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

Make sure to deallocate the returned value.

确保释放返回的值。

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

最好只返回 astd::string以便您的函数的用户不必担心内存分配/释放。

while(input != '
while(input != '
while(*input != '
a += input[i];
input++;
i++;
') {
'){
'){

回答by Christian Hackl

Don't use char*. Use std::string, like all other here are telling you. This will eliminate all such problems.

不要使用char*. 使用std::string,就像这里所有其他人告诉你的一样。这将消除所有此类问题。

However, for the sake of completeness and because you want to understand the background, let's analyse what is going on.

但是,为了完整起见,并且因为您想了解背景,让我们分析一下发生了什么。



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

You probably mean:

你可能的意思是:

char* getHyphen(const char* input)

Your code compares the inputpointer itself to \0, i.e. it checks for a null-pointer, which is due to the unfortunate automatic conversion from a \0char. If you tried to compare with, say, 'x'or 'a', then you would get a compilation error instead of runtime crashes.

您的代码将input指针本身与进行比较\0,即它检查空指针,这是由于不幸的从\0char. 如果您尝试与,例如,'x'或进行比较'a',那么您将收到编译错误而不是运行时崩溃。

You want to dereferencethe pointer via *inputto get to the charpointed to.

您想通过取消引用指针*input以到达char指向的对象。

auto hyphenated( string const& input )
    -> string
string( "Blah" )

This will also not work. You increment the inputpointer, yet with [i]you advance even further. For example, if inputhas been incremented three times, then input[3]will be the 7th character of the original array passed into the function, not the 4th one. 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.

这也行不通。您增加input指针,但随着[i]进一步前进。例如,如果input已经增加了 3 次,那么input[3]将是传递给函数的原始数组的第 7 个字符,而不是第 4 个字符。当您离开数组的边界时,这最终会导致未定义的行为。未定义的行为也可能是您提到的“总线错误 10”

Replace with:

用。。。来代替:

##代码##

(Actually, now that iis not used any longer, you can remove it altogether.)

(实际上,现在i不再使用它,您可以将其完全删除。)



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

让我再重复一遍:不要使用char*. 使用std::string.

回答by Cheers and hth. - Alf

Change your function declaration from

将您的函数声明从

##代码##

to

##代码##

and avoid all the problems of conversion to char const*and back.

并避免转换到char const*和返回的所有问题。

That said, you can construct a std::stringfrom a char_const*as follows:

也就是说,您可以std::string从 a构造 achar_const*如下:

##代码##

and you get back a temporary char const*by using the c_strmethod.

并且您char const*通过使用该c_str方法返回一个临时对象。

Do note that the result of c_stris only valid as long as the original stringinstance exists and is not modified. For example, applying c_strto a local stringand returning that result, yields Undefined Behavior and is not a good idea. If you absolutely must return a char*or char const*, allocate an array with newand copy the string data over with strcpy, like this: return strcpy( new char[s.length()+1], s.c_str() ), where the +1is to accomodate a terminating zero-byte.

请注意, 的结果c_str仅在原始string实例存在且未被修改时才有效。例如,应用c_str到本地string并返回该结果,会产生未定义的行为,这不是一个好主意。如果您绝对必须返回一个char*or char const*,请分配一个数组new并使用 复制字符串数据strcpy,如下所示:return strcpy( new char[s.length()+1], s.c_str() ),其中+1用于容纳终止的零字节。