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

后端 未结 6 1518
梦如初夏
梦如初夏 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

    C++11: Overload a string literal operator

    std::string operator ""_s(const char * str, std::size_t len) {
        return std::string(str, len);
    }
    
    auto s1 = "abc\0\0def";     // C style string
    auto s2 = "abc\0\0def"_s;   // C++ style std::string
    

    C++14: Use the operator from std::string_literals namespace

    using namespace std::string_literals;
    
    auto s3 = "abc\0\0def"s;    // is a std::string
    

提交回复
热议问题