Concatenate char arrays in C++
Best thing is use std::string
in C++ as other answers. If you really need to work with char try this way. didn't tested.
const char* foo = "hello";
const char* test= "how are";
char* full_text;
full_text= malloc(strlen(foo)+strlen(test)+1);
strcpy(full_text, foo );
strcat(full_text, test);
If you dont want to use string you can do it simply by taking an other array and storing both arrays in it with loop
#include<iostream>
#include<stdlib.h>
#include<cstdio>
using namespace std;
int main(){
char fname[30],lname[30],full_name[60];
int i,j;
i=0;j=0; // i is index of fname and j is index for lname
cout<<"Enter your first name: ";
gets(fname);
cout<<"Enter your last name: ";
gets(lname);
for (i;fname[i]!='\0';i++){
full_name[i] = fname[i];
}
cout<<"i ="<<i;
full_name[i]=' ';
i = i + 1;
for (i,j;lname[j]!='\0';i++,j++){
full_name[i] = lname[j];
}
cout<<"Your full name is: "<<full_name<<endl;
system("pause");
return 0;
}
Yes, in C++ use the +
operator for string concatenation.
But this will not work:
char[] + char[] + char[]
convert one array to std::string and it will:
std::string(char[]) + char[] + char[]
E.g.:
#include <iostream>
int main()
{
const char a[] = "how ";
const char b[] = "are ";
const char c[] = "you ";
std::cout << std::string( a + b + c ) << "\n"; // Error
std::cout << std::string(a) + b + c << "\n"; // Fine
}
In C++, use std::string
, and the operator+
, it is designed specifically to solve problems like this.
#include <iostream>
#include <string>
using namespace std;
int main()
{
string foo( "hello" );
string test( "how are" );
cout << foo + " , " + test;
return 0;
}