changing char to wstring, how?
Thanks for the prompt response Roland.
I read the http site and it does exactly what I needed, however, I
wonder if there is pure C++ way to do this, do you know?
My test run compiles, but I get a segmentation fault.
gdb.exe reports
#0 0x77c1d2b9 in msvcrt!mblen
What am I doing wrong?
Any body!!
using namespace std;
std::wstring ctow(const char* src) wchar_t* dest;
int i = mbstowcs(dest, src, sizeof(src));
return dest;
>
int main(int argc, char *argv[])
const char* str = «hola»;
std::wstring wstr;
wstr = ctow(str);
system(«PAUSE»);
return EXIT_SUCCESS;
>
My test run compiles, but I get a segmentation fault.
gdb.exe reports
#0 0x77c1d2b9 in msvcrt!mblen
What am I doing wrong?
Any body!!
using namespace std;
std::wstring ctow(const char* src) wchar_t* dest;
int i = mbstowcs(dest, src, sizeof(src));
‘dest’ is not pointing anywhere.
My test run compiles, but I get a segmentation fault.
gdb.exe reports
#0 0x77c1d2b9 in msvcrt!mblen
What am I doing wrong?
Any body!!
You don’t understand pointers and arrays. You need to C++ text book.
using namespace std;
std::wstring ctow(const char* src) wchar_t* dest;
Unitinialised pointer, you need to allocate some memory.
int i = mbstowcs(dest, src, sizeof(src));
sizeof(src) gives the sizeof the pointer (four bytes) not the size of
the string.
It would be better like this, using a vector to allocate the necessary
memory.
std::wstring ctow(const char* src) std::vector dest(how_ever_many_bytes_you_need);
int i = mbstowcs(&dest[0], src, strlen(src));
return std::wstring(&dest[0]);
>
I don’t know how you get the value of ‘how_ever_many_bytes_you_need’,
I’ll leave you to work that out.
If you are a newbie, then don’t use pointers when you don’t have to,
especially when you don’t understand them.
Cpp char to wstring
I have populated values wish some strings and trying to convert one index into a wstring as shown below:
However im not able to cast it.
Please suggest appropriate casting for this.
It’s not just a problem of casting; it’s more a problem of encoding. With MS Visual C++, std::wstring can be used to store Unicode UTF-16 strings. What is the encoding of the char* string? Is it UTF-8? Is it ANSI? Is it some other code page? First, you have to clarify the encoding of the source string. To convert to Unicode UTF-16 and store in std::wstring, you can use ATL conversion helpers like CA2CW, specifying an encoding as second parameter; e.g. to convert from UTF-8 to UTF-16, you may want to use some code like this:
#include const char * sourceUtf8; . std::wstring utf16( CA2CW(sourceUtf8, CP_UTF8) );
I have populated values wish some strings and trying to convert one index into a wstring as shown below:
However im not able to cast it.
Please suggest appropriate casting for this.
The first thing you should ask yourself is why you are using char* strings at all. If you were using wchar_t strings then you could just do
wchar_t** values;
// fill values
wstring name = values[0];
You cannot convert between char strings and wchar_t strings by casting. You have to use an actual conversion. Take a look at CA2W converter class.
David Wilkinson | Visual C++ MVP
- Proposed as answer by Helen Zhao Friday, February 17, 2012 7:24 AM
- Marked as answer by Helen Zhao Wednesday, February 22, 2012 1:29 AM
I’d suggest the ATL helper classes instead: they are very convenient, for example they properly calculate destination string length, they use a «small string» optimization (using fast stack memory instead of allocating on the heap for small strings), and manage allocated string in a RAII way. An alternative method (showing the use of raw Win32 API’s and STL strings, without ATL helpers) can be found here: https://msmvps.com/blogs/gdicanio/archive/2011/02/04/conversion-between-unicode-utf-8-and-utf-16-with-stl-strings.aspx Giovanni
Hi Bharat, As far as I know, string is a type that describes a specialization of the template class basic_string with elements of type char as a string, wstring is a type that describes a specialization of the template class basic_string with elements of type wchar_t as a wstring.nter to char type which pointes to the initial address of a string. If you want to know more information about converting between string and wstring, you can refer to the link: http://www.codeproject.com/Articles/17573/Convert-Between-std-string-and-std-wstring-UTF-8-a. Or you can refer to the following code snippets:
// std::string -> std::wstring std::string s("string"); std::wstring ws; ws.assign(s.begin(), s.end()); // std::wstring -> std::string std::wstring ws(L"wstring"); std::string s; s.assign(ws.begin(), ws.end());
Thanks for your active participation in the MSDN Forum.
Best regards,
Helen Zhao [MSFT]
MSDN Community Support | Feedback to us
- Proposed as answer by Helen Zhao Tuesday, February 21, 2012 8:31 AM
- Marked as answer by Helen Zhao Wednesday, February 22, 2012 1:29 AM
All replies
I have populated values wish some strings and trying to convert one index into a wstring as shown below:
However im not able to cast it.
Please suggest appropriate casting for this.
The first thing you should ask yourself is why you are using char* strings at all. If you were using wchar_t strings then you could just do
wchar_t** values;
// fill values
wstring name = values[0];
You cannot convert between char strings and wchar_t strings by casting. You have to use an actual conversion. Take a look at CA2W converter class.
David Wilkinson | Visual C++ MVP
- Proposed as answer by Helen Zhao Friday, February 17, 2012 7:24 AM
- Marked as answer by Helen Zhao Wednesday, February 22, 2012 1:29 AM
Конвертировать const char * в wstring
Я работаю над собственным расширением для флеш-приложения на основе цинка, и мне нужно преобразовать const char* в wstring . Это мой код:
mdmVariant_t* appendHexDataToFile(const zinc4CallInfo_t *pCallInfo, int paramCount, mdmVariant_t **params) < if(paramCount >= 2) < const char *file = mdmVariantGetString(params[0]); const char *data = mdmVariantGetString(params[1]); return mdmVariantNewInt(native.AppendHexDataToFile(file, data)); >else < return mdmVariantNewBoolean(FALSE); >>
Но native.AppendHexDataToFile() требуется два wstring . Я не очень хорошо разбираюсь в С++, и я думаю, что все эти разные типы строк совершенно сбивают с толку, и я не нашел в сети ничего полезного. Поэтому я прошу вас, ребята, как это сделать. Изменить: Строки — это UTF-8, и я использую OSX и Windows XP/Vista/7
Прежде чем пытаться разобраться с символами и широкими символами, вы должны быть в состоянии ответить на следующий вопрос: как закодированы строки и какое преобразование вы собираетесь делать?
6 ответов
Я рекомендую использовать std::string вместо строк стиля C ( char* ), где это возможно. Вы можете создать объект std::string из const char* , просто передав его его конструктору.
Как только у вас есть std::string , вы можете создать простую функцию, которая преобразует std::string , содержащую многобайтовые символы UTF-8, в std::wstring , содержащую закодированные точки UTF-16 (16-битное представление специальных символов из std::string ).
Есть больше способов, как это сделать, здесь, используя функцию MultiByteToWideChar:
std::wstring s2ws(const std::string& str)
Отказ от ответственности: MultiByteToWideChar — это функция только для Windows. (OP использует Windows, но вопрос помечен только c++ )
@huahsin68 huahsin68 Это все еще лучшая конверсия в Windows. Как говорит MS здесь : «Ваше приложение может конвертировать между кодовыми страницами Windows и кодовыми страницами OEM, используя стандартные функции библиотеки времени выполнения C. Однако использование этих функций представляет риск потери данных, потому что символы, которые могут быть представлены каждой кодовой страницей, делают не совсем совпадает » Однако мне интересно, следует ли использовать кодовую страницу CP_ACP при преобразовании строк, полученных с помощью функций WINAPI . A () (например, из GetWindowTextA)
AFAIK работает только с С++ 11 и выше:
std::wstring stringToWstring(const std::string& t_str) < //setup converter typedef std::codecvt_utf8convert_type; std::wstring_convert converter; //use converter (.to_bytes: wstr->str, .from_bytes: str->wstr) return converter.from_bytes(t_str); >