Simple Stuff

From IrrWizard

Jump to: navigation, search

Contents

Convert std::string to wchar_t*

std::wstring output;
... 
//! convert a std::string to wchar_t* 
const wchar_t* convertChar(std::string text)
{
   size_t size = ::mbstowcs(NULL,&text[0],text.length());
   output.resize(size);
   ::mbstowcs(&output[0],&text[0],text.length());
   return output.c_str();
}

The above code is very unsafe. First of all, the pointer returned by c_str() only remains valid until the next time the string object is modified. Attempting to modify a std::string via a pointer to the first element is also unsafe, since the C++ standard does not guarantee that std::string stores its characters in a single, contiguous buffer. Only std::vector makes that guarantee. Rather than getting the size by passing NULL as dest, you can also guarantee that the temporary dest buffer will have sufficient room ahead of time by assuming the worst case transliteration results, one wide char for each narrow char, which will be a typical result for most code pages anyway.

Recommended instead:

//! convert a std::string to wchar_t* 
const wchar_t* convertChar(std::string text)
{
   std::vector<std::w_char_t> output( text.size() + 1 );
   std::size_t char_count = ::mbstowcs(&(output.front()),text.c_str(),dest.size());
   return std::wstring(&(output.front()),char_count);
}

Convert int to std::string

// convert int to std::string  
int i = 10; 
ostringstream myStream; 
myStream << i << flush; 
std::string index = myStream.str(); 


Convert int to wchar_t

wchar_t wcTemp[1025]; 
int i = 10;
swprintf(wcTemp,1024,L"%d",i); // Microsoft compiler (Visual Studio)
swprintf(wcTemp,L"%d",i);      // minGW compiler (Dev C++)

sprintf and its variants are inherently unsafe, since there is no way to guarantee sufficient buffer for all format strings, and as seen above by the compiler-specific lines is often less than fully portable.

Why not just do it the same as int to string above, except using a wstring and wostringstream?

// convert int to std::string  
int i = 10; 
wostringstream out; 
out << i << flush;
std::wstring index = out.str();

Convert wchar_t to c8/c_str

stringc myString(wchar_t*); 
c8* = myString.c_str();

This only works if all widechars have values that fit into a narrow char.

Personal tools