c-str

Returning 'c_str' from a function

白昼怎懂夜的黑 提交于 2019-11-27 15:10:47
This is from a small library that I found online: const char* GetHandStateBrief(const PostFlopState* state) { static std::ostringstream out; // ... rest of the function ... return out.str().c_str() } In my code I am doing this: const char *d = GetHandStateBrief(&post); std::cout<< d << std::endl; Now, at first d contained garbage. I then realized that the C string I am getting from the function is destroyed when the function returns because std::ostringstream is allocated on the stack. So I added: return strdup( out.str().c_str()); And now I can get the text I need from the function. I have

string c_str() vs. data()

故事扮演 提交于 2019-11-26 21:41:36
I have read several places that the difference between c_str() and data() (in STL and other implementations) is that c_str() is always null terminated while data() is not. As far as I have seen in actual implementations, they either do the same or data() calls c_str() . What am I missing here? Which one is more correct to use in which scenarios? Scott Langham The documentation is correct. Use c_str() if you want a null terminated string. If the implementers happend to implement data() in terms of c_str() you don't have to worry, still use data() if you don't need the string to be null

Returning 'c_str' from a function

一世执手 提交于 2019-11-26 17:05:01
问题 This is from a small library that I found online: const char* GetHandStateBrief(const PostFlopState* state) { static std::ostringstream out; // ... rest of the function ... return out.str().c_str() } In my code I am doing this: const char *d = GetHandStateBrief(&post); std::cout<< d << std::endl; Now, at first d contained garbage. I then realized that the C string I am getting from the function is destroyed when the function returns because std::ostringstream is allocated on the stack. So I

string c_str() vs. data()

青春壹個敷衍的年華 提交于 2019-11-26 06:25:43
问题 I have read several places that the difference between c_str() and data() (in STL and other implementations) is that c_str() is always null terminated while data() is not. As far as I have seen in actual implementations, they either do the same or data() calls c_str() . What am I missing here? Which one is more correct to use in which scenarios? 回答1: The documentation is correct. Use c_str() if you want a null terminated string. If the implementers happend to implement data() in terms of c