C ++中C strcpy的等价物

时间:2013-10-02 04:07:19

标签: c++ c

我有一个C代码,

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

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

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

C ++中strcpy的等价物是什么?

2 个答案:

答案 0 :(得分:5)

您可以使用std :: string

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

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


}

std :: string是标准的C ++字符串类型,它会像你那样处理复制!

答案 1 :(得分:3)

如果您希望使用char *而不是std :: string,<algorithm>的通用方法是std::copy

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

当然,如果hello的内容是动态确定的,strlen(hello) + 1)可以代替6。

但是,在一天结束时,简单地使用strcpy可能不会出错。