-1

So I have this issue

//This holds 5 messages submitted prev by the user, temporarily stored
string arrayOfMessages[5];

lets say

arrayOfMessages[0]="This is my message"//The message in the first position.

I need to copy arrayOfMessages[0] to an array of char like this one;

char message [20];

I tried using strcpy(message,arrayOfMessages[0]) but I get this error :

error: cannot convert 'std::__cxx11::string' {aka 'std::__cxx11::basic_string<char>'} to 'const char*'|

Anyone know how I can accomplish this or if I'm doing something wrong, I cant set the string to be a const char bc the message was imputed prev by the user so it changes every time you run the program thus cannot be a constant variable.

Benny K
  • 868
  • 6
  • 18

2 Answers2

1

There are many ways of doing it

By using the c_str() function of the string class

string message = "This is my message";
const char *arr;
arr = message.c_str();

By copying all the characters from the string to the char array

string message = "This is my message";
char arr[200];
for(int i = 0; i < 200 && message[i] != '\0'; i++){
    arr[i] = message[i];
}

Be careful with the array sizes if you use the second approach. You can also make it a function in order to make it easier to use

 void copyFromStringToArr(char* arr, string str, int arrSize){
     for(int i = 0; i<arrSize && str[i] != '\0'; i++){
         arr[i] = str[i];
     }
 }

So in your case you can just call the function like this:

copyFromStringToArr(message,arrayOfMessages[0],20);

Also I am sure there are many more ways to do it but these are the ones I would use.

Marko Borković
  • 1,884
  • 1
  • 7
  • 22
  • I cant use the either bc i have to the same for 5 messages i cant use const char * in the variable. And the second option wonk work bc the string is located in an array thus i cant no use message [i] to copy , this is a one dimensional array of 5 strings – CHstudent22 Jul 30 '20 at 10:13
  • You can still use the [i] you just have to do it like this for example: `arrayOfMessages[0][i]`. Because array of strings can be treated like a 2D array – Marko Borković Jul 30 '20 at 10:17
0

To copy the contents of std::string into a char[], use c_str():

std::string str = "hello";

char copy[20];
strcpy(copy, str.c_str());

But the datatype of copy must be only char* and not const char*. If you want to assign it to a const char*, then you can use direct assignment:

std::string str = "hello";
const char *copy = str.c_str();
Rohan Bari
  • 7,482
  • 3
  • 14
  • 34