0

ascii string Forlì

and using the below loop

string s = "Forlì";
for(size_t i = 0; i < s.size(); i++) {
    printf("% d", s[i]);
}

wstring s = L"Forlì";

for(size_t i = 0; i < s.size(); i++) {
    printf("% d", s[i]);
}

this is what I get

70 111 114 108 -61 -84    //string
70 111 114 108 236        //wstring

Now I want to convert between these types without changing whatever values they are printing above(not some different encoding). Since I'm not using windows or c++11, i found the below routines which gives me unsatisfactory results

std::wstring s2ws(const std::string& s) {
    const char* _Source = s.c_str();
    size_t _Dsize = mbstowcs(NULL, _Source, 0) + 1;
    wchar_t *_Dest = new wchar_t[_Dsize];
    wmemset(_Dest, 0, _Dsize);
    mbstowcs(_Dest,_Source,_Dsize);
    std::wstring result = _Dest;
    delete []_Dest;
    return result;
}

std::wstring s2ws(const std::string& s) {
    wstring w;
    w.assign(s.begin(), s.end());
    return w;
}

When I print the converted string using 1st routine it does not output anything while the second routine does not convert it to wstring(the -61,-84 do not get changed to 236).

How can I do this conversion properly? even an algorithm to manipulate those numbers without any library function will suffice...

rockstarjindal
  • 293
  • 1
  • 5
  • 15
  • http://stackoverflow.com/questions/2573834/c-convert-string-or-char-to-wstring-or-wchar-t – Support Ukraine Mar 04 '15 at 09:59
  • Have you yourself seen the answer, the top one uses c++11, many others require Windows, rest 2 strategies i have mentioned in my question. I need to find what is incorrect in my code – rockstarjindal Mar 04 '15 at 10:23
  • 1
    Assuming you're trying to convert regular UTF8, I think you're missing establishing locale before performing your conversion. [Is **that**](http://coliru.stacked-crooked.com/a/7cdb2197a791b1d5) what you're trying to accomplish? – WhozCraig Mar 04 '15 at 10:33
  • Yes, precisely so. Thank you. Can you tell me what is the scope of setlocale function, i mean i don't want to change the original locale of the whole application, just at that particular function. – rockstarjindal Mar 04 '15 at 12:45
  • You can read [the documentation](http://en.cppreference.com/w/cpp/locale/setlocale) of the function . as I recall, its global for the type you're specifying. And there are potential threading issues as well. The example I showed is somewhat poor in that it doesn't save off a copy of the old locale for that type to revert once you're done using it, so you should consider that as well. Anyway, best of luck. – WhozCraig Mar 04 '15 at 16:11

0 Answers0