How to copy a char array to string or int * (void *) in C ++?

I have multiple char arrays to copy into one string, either void * or int *. For example,

char c1[] = "Hello";
char c2[] = "World";
char c3[] = "!!!!";

      

I want to copy to one int * (void *) or string.

+3


source to share


3 answers


In C ++ you can just use + operator

to add lines



string a = "abc";
string b = "dfg";
string c = a + b;
cout << c << endl;

      

+2


source


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


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







All Articles