-1

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 ?

user3443063
  • 1,455
  • 4
  • 23
  • 37

1 Answers1

1

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();
}
Ruks
  • 3,886
  • 1
  • 10
  • 22
  • No need for the pointer. `auto myfun(std::wstring mystr) -> std::wstring { std::wostringstream out; auto const w = sizeof(wchar_t) * 2; for (auto c : mystr) { out << L"(" << std::hex << std::setw(w) << std::setfill(L'0') << std::uppercase << +c << L")"; } return out.str(); }` – Eljay Aug 28 '21 at 14:56
  • You should use [`std::wostringstream`](https://en.cppreference.com/w/cpp/io/basic_ostringstream) instead, since you don't use the input capabilities of `std::wstringstream`. – Remy Lebeau Aug 28 '21 at 19:06