I am having a little bit of trouble trying to implement a certain assignment based on which string argv[1] equals.
int _tmain(int argc, _TCHAR* argv[]) //wchar_t
{
if (argc != 2)
exit(1);
if (argv[1] == L"-foo")
printf("Success!\n");
wprintf(argv[1]);
printf("\n");
system("pause");
return 0;
}
If I run the executable with the argument “-foo”, I receive the following output:
-foo
It should be:
Success!
-foo
The string is exactly how I want it to be, but the if-condition remains to be false. Are wchar_t strings simply not comparable using the == operator? If so, how do I compare them properly?
To answer the underlying question you raised:
No they aren’t, neither are “ANSI” strings, i.e. using the
chartype as the basis. Remember, a C string (bothwchar_tandcharbased) is a pointer. This means with==you were comparing two pointer values that were definitely not equal. One, after all, is a literal string (i.e. inside your program image) while the other is allocated somewhere on the heap. So they are definitely two different entities.If you wanted to use the
==you would have to use a language such as C++ with the STL classstd::string(orstd::basic_string<_TCHAR>) or (on Windows) the ATL classCString(or ratherCStringT). These classes are sometimes referred to as smart string classes and use the C++ facility of overriding theoperator==(). However, you should keep in mind that semantics differ depending on implementation, so not every smart string class will compare the string contents. Some might merely compare the equality ofthis(i.e. is it the same instance), while others may compare the string contents case-insensitive or case-sensitive at their discretion.To compare C strings you have the following functions available for your use-case:
char) strings:strcmp,_stricmp(and the “counted” variants:_strncmp,_strnicmp… there are more)wchar_t) strings:wcscmp,_wcsicmp(and the “counted” variants:_wcsncmp,_wcsnicmp… there are more)TCHAR) strings:_tcscmp,_tcsicmp(and the “counted” variants:_tcsncmp,_tcsnicmp… there are more)You can remember these prefixes:
str-> stringwcs-> wide character stringtcs-> T character stringSide note: with
#include <tchar.h>andwindows.hthe macrosTEXTand_Tare equivalent and used to declare a string literal that will either be “ANSI” or Unicode depending on the defines at build-time. The same holds for_TCHARandTCHARapparently, whereas the latter appears to be favored in the Win32 API context.So a Unicode build will expand
_T("something")toL"something", while the “ANSI” build will expand it to"something".As to TCHAR, consider reading through the arguments put forth in: Is TCHAR still relevant? (pointed out by rubenvb) There are valid points for and against
TCHAR/_TCHARuse and you should make a decision and stick with it – i.e. be consistent.