How to copy a string of std::string type in C++?
You shouldn't use strcpy()
to copy a std::string
, only use it for C-Style strings.
If you want to copy a
to b
then just use the =
operator.
string a = "text";
string b = "image";
b = a;
strcpy is only for C strings. For std::string you copy it like any C++ object.
std::string a = "text";
std::string b = a; // copy a into b
If you want to concatenate strings you can use the +
operator:
std::string a = "text";
std::string b = "image";
a = a + b; // or a += b;
You can even do many at once:
std::string c = a + " " + b + "hello";
Although "hello" + " world"
doesn't work as you might expect. You need an explicit std::string to be in there: std::string("Hello") + "world"
strcpy example:
#include <stdio.h>
#include <string.h>
int main ()
{
char str1[]="Sample string" ;
char str2[40] ;
strcpy (str2,str1) ;
printf ("str1: %s\n",str1) ;
return 0 ;
}
Output: str1: Sample string
Your case:
A simple =
operator should do the job.
string str1="Sample string" ;
string str2 = str1 ;
Caesar's solution is the best in my opinion, but if you still insist to use the strcpy
function, then after you have your strings ready:
string a = "text";
string b = "image";
You can try either:
strcpy(a.data(), b.data());
or
strcpy(a.c_str(), b.c_str());
Just call either the data()
or c_str()
member functions of the std::string
class, to get the char*
pointer of the string object.
The strcpy()
function doesn't have overload to accept two std::string
objects as parameters.
It has only one overload to accept two char*
pointers as parameters.
Both data
and c_str
return what does strcpy()
want exactly.