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

前端 未结 4 1946
滥情空心
滥情空心 2020-12-24 12:25

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         


        
4条回答
  •  夕颜
    夕颜 (楼主)
    2020-12-24 13:05

    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.

提交回复
热议问题