Reputation: 46363
I'm using C++ (Windows environment). I have a :
LPCWSTR mystring;
This works :
mystring = TEXT("Hello");
But how to do this ? :
mystring = ((((create a new string with text = the content which is in another LPCWSTR 'myoldstring'))))
Thanks a lot in advance!
PS :
mystring = myoldstring;
would work , but it would not create a new string, it would be the same pointer. I want to create a new string !
Upvotes: 0
Views: 870
Reputation: 14049
LPTSTR mystring;
mystring = new TCHAR[_tcslen(oldstring) + 1];
_tcscpy(mystring, oldstring);
... After you are done ...
delete [] mystring;
This is a complete program
#include <tchar.h>
#include <windows.h>
#include <string.h>
int main()
{
LPCTSTR oldstring = _T("Hello");
LPTSTR mystring;
mystring = new TCHAR[_tcslen(oldstring) + 1];
_tcscpy(mystring, oldstring);
// Stuff
delete [] mystring;
}
It compiles fine with cl /DUNICODE /D_UNICODE a.cpp
I used tchar
macros. If you don't want to use it, then
#include <windows.h>
#include <string.h>
int main()
{
LPCWSTR oldstring = L"Hello";
LPWSTR mystring;
mystring = new WCHAR[wcslen(oldstring) + 1];
wcscpy(mystring, oldstring);
// Stuff
delete [] mystring;
}
Compiles fine with cl a.cpp
Upvotes: 2
Reputation: 490663
To use C++ standard strings, you need to include the <string>
header. Since you're dealing with LPCWSTR
(emphasis on the W
part of that) you're dealing with wide characters, so you want to use wide strings (i.e., std::wstring
instead of std::string
).
#include <string>
#include <iostream>
#include <windows.h>
int main() {
LPCWSTR x=L"This is a string";
std::wstring y = x;
std::wcout << y;
}
Upvotes: 2
Reputation: 1102
what about
string myNewString = std::string(myOldString);
Just using the copy constructor of the string library.
Upvotes: 0