Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c++

string

copy

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

like image 346
Muhammad Arslan Jamshaid Avatar asked Oct 01 '12 18:10

Muhammad Arslan Jamshaid


People also ask

How do I copy one string to another string 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.

Does std::string make a copy?

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.

Is there std::string in C?

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.

How do I copy a string into another string?

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 .


2 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; 
like image 79
Caesar Avatar answered Sep 21 '22 01:09

Caesar


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"

like image 23
bames53 Avatar answered Sep 19 '22 01:09

bames53