c++hexwchar-twstring

c++ How to read a wchar_t* to into a std::wsting variable and print in HEX


In main I have a wstring mystr that contains unicode characters.

int main()
{
   std::wcout << std::hex << 16 << endl;
   std::wstring mystr = L"abc - ";
   result = myfun(mystr);

   // here I want to print out my variable result 
   //std::wcout << hex<<result;
}

I also have a function myfun which takes this wstring and prints out every letter (in HEX!) surrounded by brackets using a incrementfun -function. This works OK.

std::wstring myfun(std::wstring mystr){  
    wchar_t* ptrToCC = &mystr[0]    ;
    std::wstring Out    ;

    while (*ptrToCC != 0)
    {
        std::cout << "(" << std::hex << *ptrToCC << ")";       // first print is OK
        ptrToCC = incrementfun(ptrToCC);   
    }
    Out = "(" + std::hex + *ptrToCC + ")"                      // none of this not works
    Out = "(" + *ptrToCC + ")";
    Out  << "(" << std::hex << *ptrToCC << ")";

    return Out;
}

In the first print this function prints out the following line which is fine

(61)(62)(63)(20)(2d)(20)

Now I want to use the function myfun to return values to main, I tried to read the values into a variable to pass it back. But I am not able to read them into a variable and therefore I cannot print it in main. How can I read the values and print them out in main as HEX ?


Solution

  • Use a std::wstringstream:

    Edit: Edited to use range-based for loop.

    std::wstring myfun(std::wstring const& mystr) {  
        std::wstringstream out;
    
        for (auto const& ch : mystr)
            out << "(" << std::hex << static_cast<int>(ch) << ")";
    
        return out.str();
    }