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 ???
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.
char array.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).
sizeof c, if you're going to overwrite the last one with 0.std::string_view for that matter
char c[50]is not a pointer type, btw - think of it as the same thing as puttingchar c0, c1, c2, c3, c4- so you'll need to copy thestring's characters intocrather than merely assigning a pointer/reference or changechar c[50]to a pointer or reference to a heap-allocated array.std::vectorandstd::arrayand avoid raw pointers and raw arrays.strncpy(c, s.c_str(), 50);followed byc[49] = '\0';for robustness