There are two built-in string types:
- C++ strings use the std::string class (std::wstring for wide characters)
- C-style strings are const char pointers const char*) (or
const wchar_t*
)
Both can be used in C++ code. Most API's, including Windows' are written in C, and so they use char pointers rather than the std::string class.
Microsoft further hides these pointers behind a number of macros.
LPCWSTR is a Long Pointer to a Const Wide String, or in other words, a const wchar_t*.
LPSTR is a Long Pointer String, or in other words, a
char*. (not const)
They have a handful more, but they should be pretty easy to guess once you know these first few. They also have *TSTR variants, where the T is used to indicate that this might be either regular or wide chars, depending on whether UNICODE is enabled in the project. LPCTSTR resolves to LPCWSTR if UNICODE is defined, and LPCSTR otherwise.
So really, when working with strings, you just need to know the two types I listed at the top. The rest are just macros for various variants of the char pointer version.
Converting from a char pointer to a string is simple:
const char* cstr = "hello world";
std::string cppstr = cstr;
And the other way isn't much hader:
std::string cppstr("hello world");
const char* cstr = cppstr.c_str();
That is, std::string
takes a C-style string as an argument in the constructor. And it has a c_str()
member function that returns a C-style string.
Some commonly used libraries define their own string types, and in those cases, you'll have to check the documentation for how they interoperate with the "proper" string classes.
You should usually prefer the C++ std::string
class, as, unlike char pointers, they behave as strings. For example:
std:string a = "hello ";
std:string b = "world";
std:string c = a + b; // c now contains "hello world"
const char* a = "hello ";
const char* b = "world";
const char* c = a + b; // error, you can't add two pointers
std:string a = "hello worl";
char b = 'd';
std:string c = a + b; // c now contains "hello world"
const char* a = "hello worl";
char b = 'd';
const char* c = a + b; // Doesn't cause an error, but won't do what you expect either. the char 'd' is converted to an int, and added to the pointer `a`. You're doing pointer arithmetic rather than string manipulation.