I need to take an std::string that I have and convert it to a WCHAR does anyone know how to do this? Any help is appreciated
Your question is vague; wchar_t is used to store a wide character, and wstring is to store a wide string. You can't convert a string to wchar_t.
But if your aim was to convert an std::string to wchar_t*, then you need to convert your std::string to an std::wstring first, then to convert your std::wstring to const wchar_t*.
string narrow_string("A string");
wstring wide_string = wstring(narrow_string.begin(), narrow_string.end());
const wchar_t* result = wide_string.c_str();
Assuming you want to convert from the locale encoding, since you want wchar_t.
Option 1, since C++11 but deprecated in C++17:
// See https://stackoverflow.com/questions/41744559
template<class I, class E, class S>
struct codecvt_ : std::codecvt<I, E, S> { ~codecvt_ () {} };
std::wstring to_wide (const std::string &multi) {
return std::wstring_convert<codecvt_<wchar_t, char, mbstate_t>> {}
.from_bytes (multi);
}
Option 2, widely portable:
std::wstring to_wide (const std::string &multi) {
std::wstring wide; wchar_t w; mbstate_t mb {};
size_t n = 0, len = multi.length () + 1;
while (auto res = mbrtowc (&w, multi.c_str () + n, len - n, &mb)) {
if (res == size_t (-1) || res == size_t (-2))
throw "invalid encoding";
n += res;
wide += w;
}
return wide;
}
Related
I'm packing my string with this function:
std::vector<char> pack(const std::string& str) {
const uint32_t sz = str.size();
const uint32_t n_sz = htonl(sz);
std::vector<char> result(sizeof(sz) + sz);
memcpy(result.data(), &n_sz, sizeof(n_sz));
memcpy(result.data() + sizeof(sz), str.data(), sz);
return result;
}
How can i unpack it again so...i get the original string back?
I tried to do:
int len;
len = ntohl(ourbuffer.size());
char* string = ( char* )malloc(sizeof (char) * (len + 1));
string[len] = '\0';
becouse i know the function pack is using big endian. But that did not work. Can someone please show how to to unpack again??
uint32_t n_sz;
memcpy(&n_sz, ourbuffer.data(), sizeof n_sz);
const uint32_t sz = ntohl(n_sz);
std::string str(ourbuffer.data() + sizeof n_sz, sz);
I use 2 method for these conversion
// Vector to String.
VectorToString(std::vector<char> data)
{
const char* newData = &data[0];
String ^result;
result = marshal_as<String^>(newData);
return result;
}
// String to vector
StringToVector(String ^ data)
{
marshal_context ctx;
IntPtr p = Marshal::StringToHGlobalAnsi(data);
const char* pAnsi = static_cast<const char*>(p.ToPointer());
// use pAnsi
std::vector<char> result;
result.assign(pAnsi, pAnsi + strlen(pAnsi));
Marshal::FreeHGlobal(p);
return result;
}
with 2 above function I can doing convert.
can you tell me these conversion is correct? or not?
actually, this way for convert std::vector to String is best way?
you must be add #include msclr/marshal_cppstd.h
vector to String ^
vector<char> data;// this is be initialize
std::string myString = std::string(begin(data), end(data));
String^ result = marshal_as<String^>(myString);
string ^ to vector
marshal_context context;
std::vector<char> myVector;
const char* afterConvert = context.marshal_as<const char*>(data);
myVector.assign(afterConvert , afterConvert + strlen(afterConvert));
I'm converting a float to a const wchar_t *
DisplayText(ConversionUtils::FloatToWstring(fps).c_str()); // Prints garbage
DisplayText(std::to_wstring(fps).c_str()); // Doesn't print anything to the device.
with this function :
std::wstring ConversionUtils::FloatToWstring(float value) {
return std::to_wstring(value);
}
I want to get something like that :
DisplayText(ConversionUtils::FloatToConstWcharPtr(fps));
Just return by value:
std::wstring ConversionUtils::FloatToWchar(float value) {
std::string str = std::to_string(value);
return std::wstring(str.begin(), str.end());
}
Or better, use std::to_wstring() instead.
What would be the code to convert an std::string to unsigned char* and back?
str = "1234567891234567"
unsigned char* unsignedStr = ConvertStrToUnsignedCharPointer(str);
str1 = ConvertUnsignedCharToStr(unsignedStr);
str and str1 must be same with no loss of precision.
auto str1 = std::string{"1234567891234567"}; // start with string
auto chrs = str.c_str(); // get constant char* from string
auto str2 = std::string{ chrs }; // make string from char*
Unsigned char*:
auto uchrs = reinterpret_cast<unsigned char*>(const_cast<char*>(chrs));
Using vectors instead of raw pointers:
using namespace std;
auto str1 = string{"1234567891234567"};
vector<char> chars{ begin(str1), end(str1) };
vector<unsigned char> uchars;
transform(begin(str1), end(str1), back_inserter(uchars),
[](char c) { return reinterpret_cast<unsigned char>(c); });
I am copying double value into unsigned char* in the following way.
unsigned char* cmdBody;
double val = (double)-1;
std::ostringstream sstream;
sstream << val;
std::string valString = sstream.str();
unsigned int dataSize = valString.size() + 1;
cmdBody = (unsigned char*)malloc(dataSize);
memset(cmdBody, 0, dataSize);
memcpy(cmdBody, (unsigned char*)valString.c_str(), dataSize - 1);
cmdBody[dataSize - 1] = '\0';
From cmdBody I need to convert the value into double type. How to do it?
C much?
Your solution is very simple if you just use a std::string:
const auto val = -1.0; // Input double
const auto cmdBody = std::to_string(val); // Convert double to a std::string
const auto foo = std::stod(cmdBody); // Convert std::string to a double
It's important to note that there is no need to allocate, memcopy, or null-terminate when constructing a std::string. Which vastly simplifies your code.
Use std::stod, something like this:
#include <string>
double d = std::stod(cmdBody);
std::istringstream istream(std::string("3.14"));
double d;
istream >> d;
if (!istream.fail())
{
// convertion ok
}