使用strcmp将argv项与字符串文字进行比较并不像我期望的那样工作

时间:2012-04-22 14:48:57

标签: visual-studio-2010 visual-c++ argv strcmp

我对Visual C ++很陌生,所以这可能是一个'小学生'错误,但是下面的代码没有像我预期的那样执行:

#include "stdafx.h"
#include <string.h>

int _tmain(int argc, _TCHAR* argv[])
{
    if (strcmp((char*)argv[1], "--help") == 0)
    {
        printf("This is the help message."); //Won't execute
    }
    return 0;
}

名为Test.exe的可执行文件按如下方式启动

Test.exe --help

我期待消息This is the help message.,但我没有看到它 - 调试显示if条件为-1而不是0,正如我所期望的那样。我做错了什么?

1 个答案:

答案 0 :(得分:1)

好的,我已经知道发生了什么。 argv[]数组声明为TCHAR*,这是一个根据是否已为项目启用Unicode来调整类型的宏(如果是wchat_tchar如果不是)。我试图使用的strcmp函数是非Unicode字符串比较,而wcscmp是Unicode等价物。 _tcscmp函数根据Unicode设置使用适当的字符串比较函数。如果我将strcmp替换为_tcscmp,问题就解决了!

#include "stdafx.h"
#include <string.h>

int _tmain(int argc, _TCHAR* argv[])
{
    if (_tcscmp(argv[1], _T("--help")) == 0)
    {
        printf("This is the help message."); //Will execute :)
    }
    return 0;
}

如果启用了Unicode,_T函数会将参数转换为Unicode。

另请参阅:Is it advisable to use strcmp or _tcscmp for comparing strings in Unicode versions?