How to copy a char array to string or int * (void *) in C ++?
3 answers
It would be much easier with a C ++ namespace std::string
and std::stringstream
namespace class :
#include <sstream>
#include <string>
std::string c1("Hello");
std::string c2("World");
std::string c3("!!!!");
std::stringstream ss;
ss << c1 << c2 << c3;
std::string finalString = ss.str();
You cannot copy them to int*
or void*
, because they are completely different types.
+1
source to share
In my opinion the simplest way is
#include <iostream>
#include <string>
#include <cstring>
int main()
{
char c1[] = "Hello";
char c2[] = "World";
char c3[] = "!!!!";
size_t n = 0;
for ( char *t : { c1, c2, c3 } ) n += strlen( t );
std::string s;
s.reserve( n );
for ( char *t : { c1, c2, c3 } ) s += t;
std::cout << s << std::endl;
return 0;
}
Output signal
HelloWorld!!!!
+1
source to share