I have the following code and would like to end up with a char such as: "Hello, how are you?" (this is just an example of what I'm trying to achieve)
How can I concatenate the 2 char arrays plus adding the "," in the middle and the "you?" at the end?
So far this concatenates the 2 arrays but not sure how to add the additional characters to my final char variable I want to come up with.
#include "stdafx.h"
#include <iostream>
#include <string>
using namespace std;
int _tmain(int argc, _TCHAR* argv[])
{
char foo[] = { "hello" };
char test[] = { "how are" };
strncat_s(foo, test, 12);
cout << foo;
return 0;
}
EDIT:
This is what I came up with after all your replies. I'd like to know if this is the best approach?
#include "stdafx.h"
#include <iostream>
#include <string>
using namespace std;
int _tmain(int argc, _TCHAR* argv[])
{
char foo[] = { "hola" };
char test[] = { "test" };
string foos, tests;
foos = string(foo);
tests = string(test);
string concat = foos + " " + tests;
cout << concat;
return 0;
}
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 love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With