String to wstring windows

Перевод string в wstring

В проекте требуется перевод строк из string в wstring, я использую такую вот конструкцию, но данная конструкция не позволяет переводить символы кириллицы так как кодировки разные, кто то знает другую конструкцию или как допилить эту

Перевод из string в wstring. Неправильная кодировка
Здорова господа! Перевожу строку из string в wstring, в строке русские символы и они выводятся в.

Из string в wstring
Как можно получить wstring-строку из string-строки? (символы в строке латинские, поэтому проблем.

Сконвертировать string в wstring
Люди подскажите пожалуйста как правильно сконвертировать string с кириллицей в wstring т.е.

Корректен ли каст из string в wstring?
Доброго вечера. Вот кусок кода: template string_t make_string(.

VrameeV, самый банальный — пройтись циклом по string и присвоить string[i] соответствующему wstring[i]

Добавлено через 2 минуты
Можно попробовать создать объект wstring, передавая ему в конструктор строку string

VrameeV, мой первый вариант неверный — извиняюсь.

Сейчас через пару минут всё будет

Добавлено через 3 минуты
VrameeV, мой шедевр

Полнейшая — хотя без проблем компилируется, я уверовал в конструктор копирования и оператор присваивания, но это не работает.

Добавлено через 12 минут
Как я и думал — весь косяк в том, что внутри std::string лежит char, а внутри std::wstring — wchar_t

Для интересующихся — это легко посмотреть в собственной среде разработки
Этот кусок, к примеру, из моей Visual Studio 15:

2 и 1 байт соответственно.

Поэтому просто скопировать символы (как я хотел в своём первом посту) из одно «байтного стринга» в «двух байтный» не получится

Соответственно эта строка покажет нам

2 и 1 байт соответственно.

размер wchar_t от системы зависит

Linux и OS X — 4 байта
Windows — 2 байта

то вывод у нас получается

3-3 ? . txt
3-3 ? . txt

Тематические курсы и обучение профессиям онлайн
Профессия Разработчик на C++ (Skillbox)
Архитектор ПО (Skillbox)
Профессия Тестировщик (Skillbox)

Спасибо, теперь буду иметь ввиду.
Но вообще, этот код — не моё творчество а просто пример из справочника по STL. В нем по-моему, ещё один пример был и возможно там даже указано про то, что вы сообщили — вникать было лень, потому как поздно было уже — спать очень хотелось , поэтому я просто вытащил код из самого первого примера — проверил — работает, ну и опубликовал.

Заказываю контрольные, курсовые, дипломные и любые другие студенческие работы здесь или здесь.

Из wchar_t* в wstring или в string
Как перевести из wchar_t* в wstring или в string ? Почему столько геморроя со строками. Есть.

Опять мучаюсь с конвертацией string в wstring
Опять парюсь с преобразованием string в wstring. Куча способов уже перепробовал, всё не то. То ли.

По поводу wchar_t, wstring, char, string и кодировок
Здравствуйте, пишу консольную либу которая будет работать с большим количеством символов в разных.

Не могу поместить в переменную wstring и string русское слово
Помогите пожалуйста , когда ввожу с клавиатуры в переменную string или wstring русское слово , то.

Wstring to string как конвертировать

Перевод строк std::string, std::wstring в Unicode (String)
Собственно столкнулся с проблемой, как корректно перевести к примеру текст из Edit1->Text в.

Конвертировать image в string
как конвертировать image в string c++

TByteDynArray конвертировать в String
Мне нужно изменить кодировку windows — 1252 на windows — 1251, для этого я воспользовался.

Читайте также:  Ножницы windows как ими пользоваться

Как LRESULT конвертировать в string на C++ Win32
Как LRESULT конвертировать в string на C++ Win32 .

Решение

Тематические курсы и обучение профессиям онлайн
Профессия Разработчик на C++ (Skillbox)
Архитектор ПО (Skillbox)
Профессия Тестировщик (Skillbox)

Заказываю контрольные, курсовые, дипломные и любые другие студенческие работы здесь или здесь.

Ошибка при присвоении argv[1] переменной string. Как конвертировать к типу string?
«call of an object of a class type without appropriate operator() or conversion functions to.

Из string в wstring
Как можно получить wstring-строку из string-строки? (символы в строке латинские, поэтому проблем.

Как конвертировать String в int
Вот например: string a = 09; Сделать что б: Int b = 9; а также: string a = 17; Сделать.

How do I convert a string to a wstring using the value of the string?

I’m new to C++ and I have this issue. I have a string called DATA_DIR that I need for format into a wstring.

Visual Studio tells me that there is no instance of constructor that matches with the argument list. Clearly, I’m doing something wrong.

I found this example online

which apparently works (no compile errors). My question is, how do I get the string value stored in DATA_DIR into the wstring constructor as opposed to something arbitrary like «hello world»?

4 Answers 4

Here is an implementation using wcstombs (Updated):

This is in reference to the most up-voted answer but I don’t have enough «reputation» to just comment directly on the answer.

The name of the function in the solution «wstring_from_bytes» implies it is doing what the original poster wants, which is to get a wstring given a string, but the function is actually doing the opposite of what the original poster asked for and would more accurately be named «bytes_from_wstring».

To convert from string to wstring, the wstring_from_bytes function should use mbstowcs not wcstombs

Regardless, this is much more easily done in newer versions of the standard library (C++ 11 and newer)

printf -style format specifiers are not part of the C++ library and cannot be used to construct a string .

If the string may only contain single-byte characters, then the range constructor is sufficient.

The problem is that we usually use wstring when wide characters are applicable (hence the w ), which are represented in std::string by multibyte sequences. Doing this will cause each byte of a multibyte sequence to translate to an sequence of incorrect wide characters.

Moreover, to convert a multibyte sequence requires knowing its encoding. This information is not encapsulated by std::string nor std::wstring . C++11 allows you to specify an encoding and translate using std::wstring_convert , but I’m not sure how widely supported it is of yet. See 0x. ‘s excellent answer.

How do you convert CString and std::string std::wstring to each other?

CString is quite handy, while std::string is more compatible with STL container. I am using hash_map . However, hash_map does not support CString s as keys, so I want to convert the CString into a std::string .

Writing a CString hash function seems to take a lot of time.

How can I do this?

EDIT:

Here are more questions:

How can I convert from wstring to CString and vice versa?

Is there any problem with this?

Additionally, how can I convert from std::wstring to std::string and vice versa?

16 Answers 16

CString to std::string :

BUT: std::string cannot always construct from a LPCTSTR . i.e. the code will fail for UNICODE builds.

Читайте также:  Как переименовать домашнюю папку linux

As std::string can construct only from LPSTR / LPCSTR , a programmer who uses VC++ 7.x or better can utilize conversion classes such as CT2CA as an intermediary.

CStringT can construct from both character or wide-character strings. i.e. It can convert from char* (i.e. LPSTR ) or from wchar_t* ( LPWSTR ).

In other words, char-specialization (of CStringT ) i.e. CStringA , wchar_t -specilization CStringW , and TCHAR -specialization CString can be constructed from either char or wide-character, null terminated (null-termination is very important here) string sources.
Althoug IInspectable amends the «null-termination» part in the comments:

NUL-termination is not required.
CStringT has conversion constructors that take an explicit length argument. This also means that you can construct CStringT objects from std::string objects with embedded NUL characters.

Solve that by using std::basic_string instead of std::string and it should work fine regardless of your character setting.

It is more effecient to convert CString to std::string using the conversion where the length is specified.

In tight loop this makes a significant performance improvement.

If you want something more C++-like, this is what I use. Although it depends on Boost, that’s just for exceptions. You can easily remove those leaving it to depend only on the STL and the WideCharToMultiByte() Win32 API call.

Is there any problem?

There are several issues:

  • CString is a template specialization of CStringT. Depending on the BaseType describing the character type, there are two concrete specializations: CStringA (using char ) and CStringW (using wchar_t ).
  • While wchar_t on Windows is ubiquitously used to store UTF-16 encoded code units, using char is ambiguous. The latter commonly stores ANSI encoded characters, but can also store ASCII, UTF-8, or even binary data.
  • We don’t know the character encoding (or even character type) of CString (which is controlled through the _UNICODE preprocessor symbol), making the question ambiguous. We also don’t know the desired character encoding of std::string .
  • Converting between Unicode and ANSI is inherently lossy: ANSI encoding can only represent a subset of the Unicode character set.

To address these issues, I’m going to assume that wchar_t will store UTF-16 encoded code units, and char will hold UTF-8 octet sequences. That’s the only reasonable choice you can make to ensure that source and destination strings retain the same information, without limiting the solution to a subset of the source or destination domains.

The following implementations convert between CStringA / CStringW and std::wstring / std::string mapping from UTF-8 to UTF-16 and vice versa:

The remaining two functions construct C++ string objects from MFC strings, leaving the encoding unchanged. Note that while the previous functions cannot cope with embedded NUL characters, these functions are immune to that.

How to convert wstring into string?

The question is how to convert wstring to string?

I have next example :

the output with commented out line is :

but without is only :

Is anything wrong in the example? Can I do the conversion like above?

EDIT

New example (taking into account some answers) is

therefore the stringstream can not be used to convert wstring into string.

17 Answers 17

Here is a worked-out solution based on the other suggestions:

This will usually work for Linux, but will create problems on Windows.

As Cubbi pointed out in one of the comments, std::wstring_convert (C++11) provides a neat simple solution (you need to #include and ):

Читайте также:  Msdn windows 10 pro 64 bit

I was using a combination of wcstombs and tedious allocation/deallocation of memory before I came across this.

update(2013.11.28)

One liners can be stated as so (Thank you Guss for your comment):

Wrapper functions can be stated as so: (Thank you ArmanSchwarz for your comment)

Note: there’s some controversy on whether string / wstring should be passed in to functions as references or as literals (due to C++11 and compiler updates). I’ll leave the decision to the person implementing, but it’s worth knowing.

Note: I’m using std::codecvt_utf8 in the above code, but if you’re not using UTF-8 you’ll need to change that to the appropriate encoding you’re using:

Beware that there is no character set conversion going on here at all. What this does is simply to assign each iterated wchar_t to a char — a truncating conversion. It uses the std::string c’tor:

As stated in comments:

values 0-127 are identical in virtually every encoding, so truncating values that are all less than 127 results in the same text. Put in a chinese character and you’ll see the failure.

the values 128-255 of windows codepage 1252 (the Windows English default) and the values 128-255 of unicode are mostly the same, so if that’s teh codepage you’re using most of those characters should be truncated to the correct values. (I totally expected á and õ to work, I know our code at work relies on this for é, which I will soon fix)

And note that code points in the range 0x80 — 0x9F in Win1252 will not work. This includes € , œ , ž , Ÿ , .

Instead of including locale and all that fancy stuff, if you know for FACT your string is convertible just do this:

Default encoding on:

My solution Steps, includes null chars \0 (avoid truncated). Without using functions on windows.h header:

  1. Add Macros to detect Platform. Windows/Linux and others
  1. Create function to convert std::wstring to std::string and inverse std::string to std::wstring

Check RawString Literals. Raw String Suffix.

Linux Code. Print directly std::string using std::cout, Default Encoding on Linux is UTF-8, no need extra functions.

On Windows if you need to print unicode. We can use WriteConsole for print unicode chars from std::wstring.

Finally on Windows. You need a powerfull and complete view support for unicode chars in console. I recommend Windows Terminal

QA

  • Tested on Microsoft Visual Studio 2019 with VC++; std=c++17. (Windows Project)
  • Tested on repl.it using Clang compiler; std=c++17.

Q. Why you not use header functions and classes?.
A. Deprecate Removed or deprecated features impossible build on VC++, but no problems on g++. I prefer 0 warnings and headaches.

Q. std ::wstring is cross platform?
A. No. std::wstring uses wchar_t elements. On Windows wchar_t size is 2 bytes, each character is stored in UTF-16 units, if character is bigger than U+FFFF, the character is represented in two UTF-16 units(2 wchar_t elements) called surrogate pairs. On Linux wchar_t size is 4 bytes each character is stored in one wchar_t element, no needed surrogate pairs. Check Standard data types on UNIX, Linux, and Windowsl.

Q. std ::string is cross platform?
A. Yes. std::string uses char elements. char type is guaranted that is same byte size in most compilers. char type size is 1 byte. Check Standard data types on UNIX, Linux, and Windowsl.

Full example code

Using Windows Terminal

Using cmd/powershell

Repl.it capture

Оцените статью