convert a char* to std::string

后端 未结 11 989
萌比男神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:42

    I need to use std::string to store data retrieved by fgets().

    Why using fgets() when you are programming C++? Why not std::getline()?

    0 讨论(0)
  • 2020-12-02 04:43
    const char* charPointer = "Hello, World!\n";
    std::string strFromChar;
    strFromChar.append(charPointer);
    std::cout<<strFromChar<<std::endl;
    
    0 讨论(0)
  • 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;
    
    0 讨论(0)
  • 2020-12-02 04:47

    If you already know size of the char*, use this instead

    char* data = ...;
    int size = ...;
    std::string myString(data, size);
    

    This doesn't use strlen.

    EDIT: If string variable already exists, use assign():

    std::string myString;
    char* data = ...;
    int size = ...;
    myString.assign(data, size);
    
    0 讨论(0)
  • 2020-12-02 04:48

    Most answers talks about constructing std::string.

    If already constructed, just use assignment operator.

    std::string oString;
    char* pStr;
    
    ... // Here allocate and get character string (e.g. using fgets as you mentioned)
    
    oString = pStr; // This is it! It copies contents from pStr to oString
    
    0 讨论(0)
提交回复
热议问题