convert a char* to std::string

后端 未结 11 987
萌比男神i
萌比男神i 2020-12-02 04:08

I need to use an std::string to store data retrieved by fgets(). To do this I need to convert the char* return value from fgets(

11条回答
  •  攒了一身酷
    2020-12-02 04:43

    I would like to mention a new method which uses the user defined literal s. This isn't new, but it will be more common because it was added in the C++14 Standard Library.

    Largely superfluous in the general case:

    string mystring = "your string here"s;
    

    But it allows you to use auto, also with wide strings:

    auto mystring = U"your UTF-32 string here"s;
    

    And here is where it really shines:

    string suffix;
    cin >> suffix;
    string mystring = "mystring"s + suffix;
    

提交回复
热议问题