Subj : Re: How do I string compare two strings, one Unicode and the other To : borland.public.cpp.borlandcpp From : D Date : Thu Sep 29 2005 03:41 am Thanks Thomas. You have given me a much greater understanding. maeder@glue.ch (Thomas Maeder [TeamB]) wrote: >"D" writes: > >> Can somebody tell me how to perform a string comparision of two >> strings, one string is Unicode and the other a char*? >> The following isn't working for me. >> Am I using the correct string comparison functions? >> >> wchar_t* name = (wchar_t*) "fred"; > >First of all, the type of "fred" is 'array of 5 char const'. Writing >over the elements of this array isn't possible directly; doing so >indirectly, e.g. after casting away the constness, has undefined >behavior. You should therefore avoid having a pointer to non-const >pointing at that array. > >Then the expression (wchar_t*) "fred" is equivalent to >reinterpret_cast("fred"). The value of this expression is >implementation-defined, and almost certainly not what you need. > > >> if (wcscmp(name, (wchar_t*) "fred") == 0) > >The function wcscmp is used to compare two wide character strings >(cf. http://tinyurl.com/935o5 aka >http://msdn.microsoft.com/library/default.asp?url=/library/en-us/vclib/html/_crt_strcmp.2c_.wcscmp.2c_._mbscmp.asp >, which may wrap). Passing it the address of an array of no-wide >characters is thus lying. You'll get undefined behavior; with a little >luck on your side, the program will crash and you won't miss the >error. > > >> { >> // never enters here. > >You are out of luck then. > >> } > > >You have to pass wcscmp() pointers into two arrays of wchar_t. E.g.: > >if (wcscmp(name,L"fred")==0) > >The prefix L in front of a string literal causes the literal's element >type to be wchar_t. > > >Whether this suggestion works depends on whether name and L"fred" have >the same encoding. You write that name's encoding is Unicode. The >encoding of L"fred" depends on the settings of the compiler and the OS >it is run on. If it's not Unicode, you'll first have to convert L"fred" >to Unicode. .