Ary*_*ian 8 c++ string const char
我刚刚开始使用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 != '\0'){
a += input[i];
input++;
i++;
}
//convert a string to char*
return NULL;
}
Run Code Online (Sandbox Code Playgroud)
bku*_*ytt 15
答:std::string该类有一个带有a的构造函数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
Run Code Online (Sandbox Code Playgroud)
首先,您不需要所有代码来std::string从输入构造 a。你可以只使用:
string a(input);
Run Code Online (Sandbox Code Playgroud)
至于返回新的char*,您可以使用:
return strdup(a.c_str()); // strdup is a non-standard function but it
// can be easily implemented if necessary.
Run Code Online (Sandbox Code Playgroud)
确保释放返回值。
最好只返回 a,std::string这样函数的用户就不必担心内存分配/释放。
std::string getHyphen(const char* input){
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
32730 次 |
| 最近记录: |