convert a char* to std::string

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

    std::string has a constructor for this:

    const char *s = "Hello, World!";
    std::string str(s);
    

    Note that this construct deep copies the character list at s and s should not be nullptr, or else behavior is undefined.

    0 讨论(0)
  • 2020-12-02 04:25
    char* data;
    std::string myString(data);
    
    0 讨论(0)
  • 2020-12-02 04:28

    I've just been struggling with MSVC2005 to use the std::string(char*) constructor just like the top-rated answer. As I see this variant listed as #4 on always-trusted http://en.cppreference.com/w/cpp/string/basic_string/basic_string , I figure even an old compiler offers this.

    It has taken me so long to realize that this constructor absolute refuses to match with (unsigned char*) as an argument ! I got these incomprehensible error messages about failure to match with std::string argument type, which was definitely not what I was aiming for. Just casting the argument with std::string((char*)ucharPtr) solved my problem... duh !

    0 讨论(0)
  • 2020-12-02 04:30

    Not sure why no one besides Erik mentioned this, but according to this page, the assignment operator works just fine. No need to use a constructor, .assign(), or .append().

    std::string mystring;
    mystring = "This is a test!";   // Assign C string to std:string directly
    std::cout << mystring << '\n';
    
    0 讨论(0)
  • 2020-12-02 04:38
    char* data;
    stringstream myStreamString;
    myStreamString << data;
    string myString = myStreamString.str();
    cout << myString << endl;
    
    0 讨论(0)
  • 2020-12-02 04:39

    Pass it in through the constructor:

    const char* dat = "my string!";
    std::string my_string( dat );
    

    You can use the function string.c_str() to go the other way:

    std::string my_string("testing!");
    const char* dat = my_string.c_str();
    
    0 讨论(0)
提交回复
热议问题