Converting a C-style string to a C++ std::string

后端 未结 6 1520
梦如初夏
梦如初夏 2020-12-14 00:42

What is the best way to convert a C-style string to a C++ std::string? In the past I\'ve done it using stringstreams. Is there a better way?

6条回答
  •  夕颜
    夕颜 (楼主)
    2020-12-14 01:21

    In general (without declaring new storage) you can just use the 1-arg constructor to change the c-string into a string rvalue :

    string xyz = std::string("this is a test") + 
                 std::string(" for the next 60 seconds ") + 
                 std::string("of the emergency broadcast system.");
    

    However, this does not work when constructing the string to pass it by reference to a function (a problem I just ran into), e.g.

    void ProcessString(std::string& username);
    ProcessString(std::string("this is a test"));   // fails
    

    You need to make the reference a const reference:

    void ProcessString(const std::string& username);
    ProcessString(std::string("this is a test"));   // works.
    

提交回复
热议问题