How to copy a string of std::string type in C++?

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++?

2

4 Answers

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; 
5

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"

7

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 ; 
1

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.

1

Your Answer

Sign up or log in

Sign up using Google Sign up using Facebook Sign up using Email and Password

Post as a guest

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

You Might Also Like