I presume this to be very simple but I cannot get it to work.
I am simply trying to convert a std::wstring to an int.
I have tried two methods so far.
The first is to use the "C" method with "atoi" like so:
int ConvertedInteger = atoi(OrigWString.c_str());
However, VC++ 2013 tells me:
Error, argument of type "const wchar_t *" is incompatable with parameter of type "const char_t *"
So my second method was to use this, per Google search:
std::wistringstream win(L"10");
int ConvertedInteger;
if (win >> ConvertedInteger && win.eof())
{
// The eof ensures all stream was processed and
// prevents acccepting "10abc" as valid ints.
}
However VC++ 2013 tells me this:
"Error: incomplete type not allowed."
What am I doing wrong here?
Is there a better way to convert a std::wstring to int and back?
Thank you for your time.
One effective way to convert a string object into a numeral int is to use the stoi() function. This method is commonly used for newer versions of C++, with is being introduced with C++11. It takes as input a string value and returns as output the integer version of it.
This LPCWSTR is Microsoft defined. So to use them we have to include Windows. h header file into our program. To convert std::wstring to wide character array type string, we can use the function called c_str() to make it C like string and point to wide character string.
The easiest solution is to use Unicode string literals and std::wstring: wstring z = L"nüşabə"; CString cs(z. c_str()); nameData. SetWindowTextW(cs);
std::wstring is used for wide-character/unicode (utf-16) strings. There is no built-in class for utf-32 strings (though you should be able to extend your own from basic_string if you need one).
No need to revert to C api (atoi
), or non portable API (_wtoi
), or complex solution (wstringstream
) because there are already simple, standard APIs to do this kind of conversion : std::stoi
and std::to_wstring
.
#include <string>
std::wstring ws = L"456";
int i = std::stoi(ws); // convert to int
std::wstring ws2 = std::to_wstring(i); // and back to wstring
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With