Conversion from char * to wchar* does not work properly

喜夏-厌秋 提交于 2019-12-13 05:53:07

问题


I'm getting a string like: "aña!a¡a¿a?a" from the server so I decode it and then I pass it to a function.

What I need to do with the message is something like loading paths depending the letters.

The header of my function is: void SetInfo(int num, char *descr[4]) so it receives one number and an array of 4 chars (sentences). To make it easier, let's say I just need to work only with descr[0].

When I debug and arrive there to SetInfo(), I get the exact message in the debugg view: "aña!a¡a¿a?a" so until here is all ok. Initially, the info I was receiving on that function, was a std::wstring so all my code working with that message was with wstrings and strings but now what I receive is a char as shown in the header. The message arrived until here ok, but if I want to work with it, then I can't because if I debug and see each position of Descr[0] then I get

 descr[0][0] = 'a'; //ok
 descr[0][1] = 'Ã '; // BAD

so I tried converting char* to wchar* with a code found here:

 size_t size = strlen(descr[0]) + 1;
 wchar_t* wa = new wchar_t[size];
 mbstowcs(wa,descr[0],size);

But then the debugger shows me that wa has:

wa wchar_t * 0x185d4be8 L"a-\uffffffff刯2e2e牵6365⽳6f73歯6f4c楲6553䈯736f獵6e6f档6946琯7361灭6569湰2e6f琀0067\021ᡰ9740슃b8\020\210=r"

which I suppose that is incorrect (I'm supossing that I have to see the same initial message of "aña!a¡a¿a?a". If this message is fine then I don't know how to get what I need...)

So my question is: how can I get that descr[0][0] = 'a' and descr[0][1] = 'ñ' ?? I can't pass char to wchar (you've already see what I got). Am I doing it wrong? Or is there any other way? I am really stuck on that so any idea will be very apreciated.

Before, when I was working with wstrings (and it worked so fine) I was doing something like this:

if (word[i]==L'\x00D1' or word[i]==L'\x00F1')  // ñ or Ñ
   path ="PathOfÑ";  

where word[i] is the same as descr[0][1] in that case but with wstrings. So with that i knew that this word[i] was the letter 'ñ'. Maybe this helps to understand what I'm doing

(btw...I'm working on eclipse, on linux. )


回答1:


The mbstowcs function work on C-style strings, and one of the things about C-style strings is that they have a special terminating character, '\0'. You don't seem to be adding this terminator to the string, leading mbstowcs to go out of bounds of the actual string and giving you undefined behavior.



来源:https://stackoverflow.com/questions/32568110/conversion-from-char-to-wchar-does-not-work-properly

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!