I used the strcpy()
function and it only works if I use C-string arrays like:
char a[6] = "text"; char b[6] = "image"; strcpy(a,b);
but whenever I use
string a = "text"; string b = "image"; strcpy(a,b);
I get this error:
functions.cpp: no matching function for call to
strcpy(std::string&, std::string&)
How to copy 2 strings of string data type in C++?
A string is a one dimensional character array that is terminated by a null character. The value of a string can be copied into another string. This can either be done using strcpy() function which is a standard library function or without it.
std::string::copyCopies a substring of the current value of the string object into the array pointed by s. This substring contains the len characters that start at position pos. The function does not append a null character at the end of the copied content.
The std::string class manages the underlying storage for you, storing your strings in a contiguous manner. You can get access to this underlying buffer using the c_str() member function, which will return a pointer to null-terminated char array. This allows std::string to interoperate with C-string APIs.
Copying one string to another - strcpystrcpy can be used to copy one string to another. Remember that C strings are character arrays. You must pass character array, or pointer to character array to this function where string will be copied. The destination character array is the first parameter to strcpy .
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"
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