How to concatenate two strings in C++?
Solution 1:
First of all, don't use char*
or char[N]
. Use std::string
, then everything else becomes so easy!
Examples,
std::string s = "Hello";
std::string greet = s + " World"; //concatenation easy!
Easy, isn't it?
Now if you need char const *
for some reason, such as when you want to pass to some function, then you can do this:
some_c_api(s.c_str(), s.size());
assuming this function is declared as:
some_c_api(char const *input, size_t length);
Explore std::string
yourself starting from here:
- Documentation of std::string
Hope that helps.
Solution 2:
Since it's C++ why not to use std::string
instead of char*
?
Concatenation will be trivial:
std::string str = "abc";
str += "another";
Solution 3:
If you were programming in C, then assuming name
really is a fixed-length array like you say, you have to do something like the following:
char filename[sizeof(name) + 4];
strcpy (filename, name) ;
strcat (filename, ".txt") ;
FILE* fp = fopen (filename,...
You see now why everybody recommends std::string
?