简体   繁体   中英

Equivalent of C strcpy in C++

I have a code in C,

struct sFoo
{
   char* name;
   char* fullname;
};

sFoo* foo = (sFoo*)malloc(sizeof(sFoo));
foo->name = (char*)malloc(10);

strcpy(foo->name, "HELLO");

What is the equivalent of strcpy in C++?

You can use std::string

int main()
{
    std::string myString = "Hello, there!";

    std::string myOtherString = myString;  //Makes a copy of myString


}

std::string is the standard C++ string type and it handles copy just like that for you!

If you wish to use char* instead of std::string, the general purpose method from <algorithm> is std::copy .

char* hello = "HELLO";
std::copy(hello, hello + 6, foo->name);

Of course, strlen(hello) + 1) may be substituted for 6 if the contents of hello are determined dynamically.

At the end of the day, however, it is likely less error prone to simply use strcpy .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM