Windows char to wchar

  1. 07-26-2002


    #1


    Registered User


    Join Date
    Mar 2002
    Posts
    112

    Hey, is there any function to convert a char to a WCHAR? I can’t get the speach function to work because it wants a WCHAR. I’ve tried type casting but it doesn’t work. I can hard code the file in but i want the user to be able to choose which file they want. To hard code it I have to add an L infront of the quation marks for the text, but how could i do something like this with a normal char?

    The code below doesn’t compile and gives me the following error:
    cannot convert parameter 1 from ‘char [255]’ to ‘const unsigned short *

    Code:

    #include <sapi.h>
    #include <iostream.h>
    #include <fstream.h>
    
    int main(int argc, char* argv[])
    {
    	ifstream file;
    	char string[255];
        ISpVoice * pVoice = NULL;
    
        if (FAILED(::CoInitialize(NULL)))
            return 0;
    
    	cout << "Enter the name of a text file you want spoken: ";
    	cin  >> string;
    
        HRESULT hr = CoCreateInstance(CLSID_SpVoice, NULL, CLSCTX_ALL, IID_ISpVoice, (void **)&pVoice);
        if( SUCCEEDED( hr ) )
        {
            hr = pVoice->Speak(string, SPF_IS_FILENAME | SPF_IS_XML, NULL);
            pVoice->Release();
            pVoice = NULL;
        }
    
        ::CoUninitialize();
        return 0;
    }

    Last edited by pinkcheese; 07-26-2002 at 09:27 PM.


  2. 07-27-2002


    #2


    Banned


    Join Date
    Aug 2001
    Location
    Visalia, CA, USA
    Posts
    3,685

    This is what you are looking for.

    Code:

    int MultiByteToWideChar(
    
        UINT CodePage,	// code page 
        DWORD dwFlags,	// character-type options 
        LPCSTR lpMultiByteStr,	// address of string to map 
        int cchMultiByte,	// number of characters in string 
        LPWSTR lpWideCharStr,	// address of wide-character buffer 
        int cchWideChar 	// size of buffer 
    );


  3. 07-27-2002


    #3


    Registered User


    Join Date
    Mar 2002
    Posts
    112

    ahhh i don’t think so…
    if i put the following code in it will compile:
    hr = pVoice->Speak(L»Hi how are you?», SPF_IS_FILENAME | SPF_IS_XML, NULL);

    but if i do something like this it won’t:
    char string[150] = «hi how are you?»;
    hr = pVoice->Speak(string, SPF_IS_FILENAME | SPF_IS_XML, NULL);

    I need to have an L infront of the quotations for it to work. How can i do that with a char?


  4. 07-27-2002


    #4


    It’s full of stars


    Join Date
    Aug 2001
    Posts
    4,829

    Surely if you are using ASCII, then the first 255 members of the UNICODE set have the same numerical value, so why can’t you simply create a 16 bit array and copy the values of the ASCII string into it?

    Wave upon wave of demented avengers march cheerfully out of obscurity unto the dream.


  5. 07-28-2002


    #5


    Banned


    Join Date
    Aug 2001
    Location
    Visalia, CA, USA
    Posts
    3,685

    *gasp* Okay, the function that I posted would work like this:

    Code:

    char string[150] = "How are you?";
    TCHAR wstring[150];
    
    MultiByteToWideChar(CP_ACP, 0, string, -1,  wstring, 150);

    Puting the L in front of the quotes (or using the _T() or TEXT() macros) tells the compiler that the string is a wide character string. It isn’t really anything special beyond that. The first part of you code worked because you were passing the correct type of string. The second didn’t work because you where passing in an ascii string.


  6. 07-28-2002


    #6


    Registered User


    Join Date
    Mar 2002
    Posts
    112

  • Forum
  • The Ubuntu Forum Community
  • Ubuntu Specialised Support
  • Development & Programming
  • Programming Talk
  • char to wchar_t — c++

  1. how can i convert a char to wchar_t?
    i also like a little sample code, and not just:
    thisfunction();

    thanks…


  2. Re: char to wchar_t — c++

    Dutchie90,

    This won’t work? (Sorry if I show my ignorance of wide characters):

    Code:

    char c;
    wchar_t w;
    w = (wchar_t)c;

    [EDIT]

    Yes, I am stupid.

    After a quick look through my handy reference book, I believe this is the function you want:

    Code:

    #include <cstdlib>
    
    int mbstowcs(wchar_t *out, const char *in, size_t size);

    Sorry I can’t give you an example. Like I said, I probably don’t know what I’m talking about when it comes to wide characters.

    Last edited by po0f; September 29th, 2006 at 08:05 AM.


  3. Re: char to wchar_t — c++

    i get this error i use the last one:
    Segmentation fault

    and the first one doesn’t work either… any other solution?


  4. Re: char to wchar_t — c++

    As long as you are only converting a single char then

    Code:

    char c = 42;
    wchar_t w = c;

    should work.

    The complexity comes when you are using encoded characters such as UTF-8.

    ACCU — for programmers who care


  5. Re: char to wchar_t — c++

    i have to do it for a simple chat thing. im using irrlicht(a game engine) for it, because i want to use irrlicht later for making games(wich is still far away i guess )… and i also want to use zoidcom(a networking api) for it, and that’s why im making a simple chat program.
    but the problem is dat irrlicht needs to use wchar_t and that i have used chars to copy username + : + his text to be put on the client.
    so i need a way to convert char to wchar_t


Bookmarks

Bookmarks

Posting Permissions

There are multiple questions on SO that address the problem on Windows. Sample posts:

  1. char* to const wchar_t * conversion
  2. conversion from unsigned char* to const wchar_t*

There is a platform agnostic method posted at http://ubuntuforums.org/showthread.php?t=1579640. The source from this site is (I hope I am not violating any copyright):

#include <locale>
#include <iostream>
#include <string>
#include <sstream>
using namespace std ;

wstring widen( const string& str )
{
    wostringstream wstm ;
    const ctype<wchar_t>& ctfacet = use_facet<ctype<wchar_t>>(wstm.getloc()) ;
    for( size_t i=0 ; i<str.size() ; ++i ) 
              wstm << ctfacet.widen( str[i] ) ;
    return wstm.str() ;
}

string narrow( const wstring& str )
{
    ostringstream stm ;

    // Incorrect code from the link
    // const ctype<char>& ctfacet = use_facet<ctype<char>>(stm.getloc());

    // Correct code.
    const ctype<wchar_t>& ctfacet = use_facet<ctype<wchar_t>>(stm.getloc());

    for( size_t i=0 ; i<str.size() ; ++i ) 
                  stm << ctfacet.narrow( str[i], 0 ) ;
    return stm.str() ;
}

int main()
{
  {
    const char* cstr = "abcdefghijkl" ;
    const wchar_t* wcstr = widen(cstr).c_str() ;
    wcout << wcstr << L'\n' ;
  }
  {  
    const wchar_t* wcstr = L"mnopqrstuvwx" ;
    const char* cstr = narrow(wcstr).c_str() ;
    cout << cstr << '\n' ;
  } 
}

You can use mbstowcs:

    wchar_t WBuf[100];
    mbstowcs(WBuf,lua_tostring( /*...*/ ),99);

or more safe:

    const char* sz = lua_tostring(/*...*/);
    std::vector<wchar_t> vec;
    size_t len = strlen(sz);
    vec.resize(len+1);
    mbstowcs(&vec[0],sz,len);
    const wchar_t* wsz = &vec[0];

Tags:

Type Conversion

C++

Irrlicht

Related

You are using an out of date browser. It may not display this or other websites correctly.
You should upgrade or use an alternative browser.

  • #1

ok, I am working on this program, and it requires me to convert a char string[20] to a wide-character type and then past a to a function and then convert the wide-character string back to a regular char string[20] in C?? I am using Visual C++ 6.0 as my IDE. Does anyone know how to do it? thanks.

  • #2

The only way I could think of to do this is to write two conversion functions. One converts an array of chars to wchar_ts and the other goes back. Below is a sample one that I wrote and compiled in MVC++ 5.0. That should work for you.

#include <string.h>
#include <wchar.h>

void wtoc(wchar_t *toConvert, char *str) {
int count = 0;
int len = wcslen(toConvert);

for(; count < len; count++) {
str[count] = (char) toConvert[count];
}
}

void ctow(char *toConvert, wchar_t *wstr) {
int count = 0;
int len = strlen(toConvert);

for(; count < len; count++) {
wstr[count] = (wchar_t) toConvert[count];
}
}

void convert(wchar_t wstr[20]) {
char copy[20];
wtoc(wstr, copy);
printf(&quot;%s\n&quot;, copy);
}

int main() {
char str[20] = &quot;I hope this works&quot;;
wchar_t wstr[20];
ctow(str, wstr);
convert(wstr);
return 1;
}

  • Advertising
  • Cookies Policies
  • Privacy
  • Term & Conditions

  • This site uses cookies to help personalise content, tailor your experience and to keep you logged in if you register.
    By continuing to use this site, you are consenting to our use of cookies.

Use the WideCharToMultiByte function to convert, which maps a unicode string to a multi-byte string. Usually suitable for use on the window platform.

#include <tchar.h>

#include <windows.h>

int _tmain(int argc, _tchar* argv[])

{

wchar_t pwstr[] =l"I am Chinese";

wchar_t pwstr2[20];

    char *pcstr = (char *)malloc(sizeof(char)*(2 * wcslen(pwstr)+1));

    memset(pcstr , 0 , 2 * wcslen(pwstr)+1 );

    w2c(pcstr,pwstr,2 * wcslen(pwstr)+1) ;

    printf("%s\n",pcstr);

c2w(pwstr2,20,pcstr);

wprintf(l"%s",pwstr2);

    free(pcstr) ;

return 0;

}

//The function to convert wchar_t* to char* is as follows:

char *w2c(char *pcstr,const wchar_t *pwstr, size_t len)

{

int nlength=wcslen(pwstr);

//Get the converted length

int nbytes = WideCharToMultiByte( 0, // specify the code page used to perform the conversion

0,         // no special flags to handle unmapped characters

pwstr,     // wide character string to convert

nlength,   // the number of wide characters in that string

NULL,      // no output buffer given, we just want to know how long it needs to be

0,

NULL,      // no replacement character given

NULL );    // we don't want to know if a character didn't make it through the translation

// make sure the buffer is big enough for this, making it larger if necessary

if(nbytes>len)   nbytes=len;

//  With the results obtained above, convert unicode characters to ascii characters

WideCharToMultiByte( 0, // specify the code page used to perform the conversion

0,         // no special flags to handle unmapped characters

pwstr,   // wide character string to convert

nlength,   // the number of wide characters in that string

pcstr, // put the output ascii characters at the end of the buffer

nbytes,                           // there is at least this much space there

NULL,      // no replacement character given

NULL );

return pcstr ;

}

//The function to convert char* to wchar_t* is as follows:

//This is to convert asii characters to unicode characters, the same principle as above

void c2w(wchar_t *pwstr,size_t len,const char *str)

{

if(str)

    {

      size_t nu = strlen(str);

      size_t n =(size_t)multibytetowidechar(cp_acp,0,(const char *)str,(int)nu,null,0);

      if(n>=len)n=len-1;

      multibytetowidechar(cp_acp,0,(const char *)str,(int)nu,pwstr,(int)n);

   pwstr[n]=0;

    }

}

 Or it is better to use this method:============I did it myself

//Convert ascii characters to unicode characters

wchar_t* Cphone_hq::ctow(wchar_t *pwstr, const char *str)

{

wchar_t* buffer;

if(str)

    {

      size_t nu = strlen(str);

      size_t n =(size_t)MultiByteToWideChar(CP_ACP,0,(const char *)str,int(nu),NULL,0);

   buffer=0;

      buffer = new wchar_t[n+1];

      //if(n>=len) n=len-1;

   ::MultiByteToWideChar(CP_ACP,0,(const char *)str,int(nu),buffer,int(n));    

   }

return buffer;

delete buffer;

}

Related knowledge points:

The emergence of Unicode is to meet the needs of software internationalization. Unicode is different from double-byte character set (DBCS).

1. Related operation functions

1. DBCS uses the following functions to manipulate strings:

CharNext-get the next character

CharPrev-get the previous character

IsDBCSLeadByte-Determine whether it is the first byte of a two-byte character

The C++ runtime library provides a series of functions starting with «_mbs» to operate DBCS. Similar functions are _mbscat and so on.

2. ANSI character set is an American standard. The C++ runtime library provides a series of functions starting with «str» ​​to manipulate this character set.

3. The C++ runtime library provides a series of functions starting with «wcs» for the Unicode character set.

Two, the corresponding data type

1. The ANSI character is defined as char.

2. The Unicode character is defined as wchar_t.

3. Use environment

1. The first thing to explain is that Win98 has very weak support for Unicode, so if you want to run a Unicode-compiled program on Win98, it may cause running errors or failures.

2. Since the kernels of Win2000 and later OS are written in Unicode, although ANSI-encoded programs can be run on it, many places need to convert ANSI to Unicode during its operation, and then call the Unicode version of the function. , Because of the existence of this conversion process, ANSI programs are not efficient. It is best to use Unicode to write programs on Win2000.

Four, write a general program

1. Use the TCHAR data type when programming. This type can be converted to ANSI or Unicode according to the definition of the pre-compiled macro.

2. Pre-compiled macros _MBCS, _UNICODE and UNICODE. _MBCS is a compiled macro for multibyte and ANSI strings. TCHAR will be converted to char at this time. _UNICODE and UNICODE are pre-compiled macros of Unicode encoding, TCHAR will be converted to wchar_t.

3. _UNICODE and UNICODE and _MBCS cannot be defined at the same time during compilation.

4. The _UNICODE macro is used for the header files of the C runtime library, and the UNICODE macro is used for the Windows header files. Generally define these two macros at the same time.

Five, conversion function

1. Convert Unicode to ANSI and use: MultiByteToWideChar.

2. Convert ANSI to Unicode and use: WideCharToMultiByte.

six,sizeof strlen wcslen tcslen comparison

  Sizeof: Get the byte length of the string, including’/0′.

  Strlen: Get the number of characters in a multi-byte string, excluding’/0′.

  Wcslen: Get the number of characters in a wide byte string, excluding’/0′.

  Tcslen: Get the length of characters in a wide-byte/multi-byte character string, not including’/0′.

—————————————————————————————————————————————————

Convert wide characters to multiple characters:

       size_t wcstombs(char *mbstr, const wchar_t *wcstr, size_t count );

Multi-character to wide character:

       size_t mbstowcs(wchar_t *wcstr, const char *mbstr, size_t count );

Another: L»ab» is a C/C++ standard macro, there is no problem in use

1. Some function interfaces in the client require unicode. Because the resources are also local, you can directly use MultiByteToWideChar or mbstowcs+setlocale conversion

2. In the case of text transmission from Chinese client->server->Korean client, the language code of the text needs to be transmitted together, and the specified code can be used on the receiving end to convert. If necessary, the server can also use this code conversion, so that multiple languages ​​can be displayed on the client at the same time.

Original link:char to wchar_t and wchar_t to char

Понравилась статья? Поделить с друзьями:
0 0 голоса
Рейтинг статьи
Подписаться
Уведомить о
guest

0 комментариев
Старые
Новые Популярные
Межтекстовые Отзывы
Посмотреть все комментарии
  • Windows 7 чистый msdn
  • Windows xp embedded sp2 iso
  • Оптимальная настройка windows 10 pro
  • Windows 10 upgrade from home to pro
  • Две синие стрелочки на ярлыках в windows 10