Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
90 views
in Technique[技术] by (71.8m points)

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

question from:https://stackoverflow.com/questions/12678819/how-to-copy-a-string-of-stdstring-type-in-c

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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;

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...