To replace std:string with const char* or char*

Asked 1 years ago, Updated 1 years ago, 99 views

Please tell me how to change std::string to const charge* or char*

string c++ char const

2022-09-21 18:05

1 Answers

If you want to use a function that writes const char* as a parameter, you can use the following method

std::string str = "I want to convert string to char*";;
const char * c = str.c_str();

In this case, it cannot be modified because it is const.

To enable modification (for example, char*, you can:

std::string str = "I want to convert string to char*";;
char * writable = new char[str.size() + 1];
std::copy(str.begin(), str.end(), writable);
writeable[str.size()] = '\0'; // Don't forget to add a zero at the end of the string
delete[] writable;

However, this method can cause memory leaks, so it's better to use the bottom one. This is a standard way of not needing another library It manages the memory on its own

std::string str = "I want to convert string to char*";
std::vector<char> writable(str.begin(), str.end());
writable.push_back('\0');
char* ptr = &writable[0];
std::cout << ptr;


2022-09-21 18:05

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.