How to concatenate two const char*?

closed account (Ey80oG1T)
Let's say that you have a const char*, and you want to add it to another const char*

1
2
3
const char* word = "hello ";
const char* word2 = "world";
word += word2;


How would I do this?
Last edited on
Well both are const, so you're not going to be modifying either of them.

You have to allocate some memory, then copy one and append the other.
1
2
3
char *s = new[strlen(word)+strlen(word2)+1];
strcpy(s,word);
strcat(s,word2);


Or just use std::string in C++.
closed account (Ey80oG1T)
The code is giving me an error. Did you mean?

 
char* s = new char[]
Pretty unlikely he meant that.

Here's a good tip for the future; we can't actually see your monitor, so when you get an error, you need to tell us what that error is.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
#include <iostream>
#include <cstring>
using namespace std;

int main() {
	
	char const* word = "beans";
	char const* word2 = "toast";
	
	char *s = new char[strlen(word)+strlen(word2)+1];
        strcpy(s,word);
       strcat(s,word2);

       cout << s;
	return 0;
}


This, of course, is bad code and contains a memory leak. You shouldn't be using char arrays. Use C++ instead. Use string.
Last edited on
Topic archived. No new replies allowed.