How to put stringstream contents into char instead string type?

后端 未结 4 661
滥情空心
滥情空心 2021-01-17 21:10

Every one know stringstream.str() need a string variable type to store the content of stringstream.str() into it .

I want to store the cont

4条回答
  •  粉色の甜心
    2021-01-17 21:37

    Why not just

    std::string s = stringstream.str();
    const char* p = s.c_str();
    

    ?

    Edit: Note that you cannot freely give the p outside your function: its lifetime is bound to the lifetime of s, so you may want to copy it.

    Edit 2: as @David suggests, copy above means copying of the content, not the pointer itself. There are several ways for that. You can either do it manually (legacy way "inherited" from C) -- this is done with the functions like std::strcpy. This way is quite complicated, since it involves manual resources management, which is usually discouraged, since it leads to a more complicated and error-prone code. Or you can use the smart pointers or containers: it can be either std::vector or std::unique_ptr/std::shared_ptr.

    I personally would go for the second way. See the discussion to this and @Oli's answer, it can be useful.

提交回复
热议问题