You are right about the null termination being a problem, I usually use the
following when interfacing with Win32:
std::vector<char> text;
text.resize(length+1);
::SendMessageA(hwnd, WM_GETTEXT, static_cast<WPARAM>(length+1),
reinterpret_cast<LPARAM>(&text[0]));
std::string string;
string.assign(&text[0], length);
I prefer to have as much of my code to be as portable as possible, hence my
preference for std::string; I prefer the MVC way of doing things where you
separate "model" and "gui" specific code, "gui" specefic e.g. MFC dialogs
are where I employ CString, otherwise I use std::string as much as possible.
I prefer an explicit call to c_str() rather than relying on ugly conversion
operators and it is up to the implementation as to whether c_str() returns a
copy or not, in VC++ it does not return a copy I believe.
/Leigh
Post by Giovanni DicanioPost by Leigh JohnstonPost by Alex Blekhman2. Pass a pointer to internal character buffer to Windows API function.
Trivial to do with std::string.. resize(...) and &s[0]
Are std::string's always NUL-terminated?
My understanding is that calling c_str() always returns a NUL-terminated
string, but I'm not sure about &s[0] (assuming 's' being an instance of
std::[w]string).
Moreover, when calling Win32 APIs that have LPCTSTR parameters, we can
pass a CString instance and implicit LPCTSTR conversion operator is
called, instead with std::[w]string it is required an additional call to
.c_str() method.
Moreover, does the .c_str() method return a *copy* of the string data?
This would cause inefficiencies...
And CString is reference counted, so using this class could save useless
deep-copies (optimizing both in space and time) that instead can happen
with std::[w]string.
Post by Leigh JohnstonPost by Alex Blekhman3. Trim a string from right and/or left.
Trivial to do with find/substr
Is it as trivial as CString::Trim/TrimeLeft/TrimRight?
I don't think so.
Post by Leigh JohnstonPost by Alex Blekhman4. Tokenize a string.
Writing a tokenizer is trivial, there is also boost
CString does it out-of-the-box.
No need for custom code.
Post by Leigh JohnstonPost by Alex BlekhmanAll the above mentioned tasks are quite easy with CString and hard with
std::string.
Wrong.
I agree with Alex.
CString interface is more convenient than std::string, especially in
contest of Win32 programming.
The benefit of STL's string class is portability of C++ code, but when you
#include <windows.h> you've already left the kingdom of portable C++ code.
Giovanni