简体   繁体   中英

in C++ How to assign an element of an array of strings to an array of char?

in c++ suppose I have:

string s[] = {"red","green","blue"} ;
char c[50] ;

I wanna make an assignment like this:

c = s[0] ;

how can I do it???

For whatever the purpose, consider if you can use std::string instead of a char array (re. array c ).

If you still want to do it, you can use strcpy or memcpy :

const char *cstr = s[0].c_str();
size_t len = strlen(cstr);
size_t len_to_copy = len > sizeof c ? sizeof c : len;

memcpy(c, cstr, len_to_copy - 1);
c[len_to_copy - 1] = 0; 

(Copying a byte less & terminating with null byte isn't necessary if 'c' doesn't need to be a C-string).

Note that this could truncate if c doesn't have any space. Perhaps std::vector<char> is better suited (depends on the use-case of course).

I would use std::copy

#include <iostream>
#include <string>

int main()
{
  std::string strings[] = {"string", "string2"};
  char s[10];
  std::copy(strings[0].begin(), strings[0].end(), s);
  std::cout << s; // outputs string
}

The advantage of using std::copy is its use of iterators.

I would use std::strncpy . It will zero terminate your buffer and wont write out of bounds.

char c[50];
std::string test_string = "maybe longer than 50 chars";
std::strncpy(c, test_string.c_str(), sizeof(c));

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