简体   繁体   中英

How can I copy the contents of string to an array of char c++?

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.

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.

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();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM