Many of us have encountered error ‘cannot convert std::string to char[] or char* data type’.
A way to do this is to copy the contents of the string to char array. This can be done with the help of c_str() and strcpy() function.
The c_str() function is used to return a pointer to an array that contains a null terminated sequence of character representing the current value of the string.
If there is an exception thrown then there are no changes in the string. But when we need to find or access the individual elements then we copy it to a char array using strcpy() function. After copying it, we can use it just like a simple array.
The length of the char array taken should not be less than the length of input string.
Я хотел бы, чтобы преобразовать string to char массив, а не char* . Я знаю, как преобразовать строку char* (через malloc или то, как я разместил его в своем коде) — но это не то, что я хочу. Я просто хочу конвертировать string to char[size] массив. Возможно ли это?
10 ответов:
самый простой способ, который я могу придумать, это:
для безопасности, вы предпочтете:
или может быть таким образом:
хорошо, я в шоке, что никто не дал хороший ответ, теперь моя очередь. Есть два случая;
A константы char массив достаточно хорош для вас так что вы идете с,
или нужно изменить массив символов so constant не в порядке, тогда просто идите с этим
оба всего операций присваивания и большую часть времени это просто что вам нужно, если вам действительно нужна новая копия, тогда следуйте ответам других товарищей.
Probably a & or something similar missing (I am noob at cpp).
How would I copy R into S
marked as duplicate by Zeta, 0x499602D2, Lol4t0, Junuxx, martin clayton Oct 12 ’12 at 21:15
This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.
2 Answers 2
There are many ways. Here are at least five:
First of all, you would have to allocate memory:
then you can use strcpy with S and R.c_str() :
You can also use R.c_str() if the string doesn’t get changed or the c string is only used once. However, if S is going to be modified, you should copy the string, as writing to R.c_str() results in undefined behavior.
Note: Instead of strcpy you can also use str::copy .