Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/string/5.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ C++;MFC如何比较if语句中的LPCTSTR?_C++_String_Mfc_Compare_Lpcstr - Fatal编程技术网

C++ C++;MFC如何比较if语句中的LPCTSTR?

C++ C++;MFC如何比较if语句中的LPCTSTR?,c++,string,mfc,compare,lpcstr,C++,String,Mfc,Compare,Lpcstr,我有以下代码: LPCTSTR strPermission = Method(); if (strPermission == L"0") { return true; } else { return false; } 在调试时,我可以看到strPermission确实等于“0”,但当我像在if语句中那样比较它时,它总是返回false 我能想到的唯一一件事是比较变量的内存地址,而不是变量值 如何将strPermission与L“0”进行比较,以便在strPermission等于

我有以下代码:

LPCTSTR strPermission = Method();

if (strPermission == L"0")
{
    return true;
}
else
{
    return false;
}
在调试时,我可以看到strPermission确实等于“0”,但当我像在if语句中那样比较它时,它总是返回false

我能想到的唯一一件事是比较变量的内存地址,而不是变量值

如何将strPermission与L“0”进行比较,以便在strPermission等于“0”时返回true


谢谢大家!

> P>你不能比较C或C++中的C风格字符串。看看这个


您正在查找的函数已被调用。

LPCTSTR
是指向
常量wchar\t
数组的指针
strPermission
指向数组的第一个字符
L“0”
是一个字符串文本,它是
const wchar\u t
的数组,衰减为
const wchar\u t
的指针。但是指针并不相等,它们指向不同的数组。这就是我们发明C++的原因。请用它

std::wstring strPermission = Method();
return (strPermission == L"0"); //works like magic!
或者,如果
Method
返回您必须保留的内容,至少要这样做

chris敦促我指出,
LPCTSTR
的类型实际上取决于编译器选项。我可以从您的代码中看出您正在使用
\u UNICODE
集进行编码,这使得它成为
常量wchar\u t*
,但是如果您希望能够使用其他选项进行编译(我想不出这样做的好理由),您应该使用
\u tcscmp
进行比较,将文本设置为
\u t(“0”)
它们将是
TCAHR
的数组。对于字符串,您必须在某处添加typedef:

#ifdef _UNICODE
    typedef std::string std::tstring 
    //you'll probably have to add more t helper functions here
#else
    typedef std::string std::wstring
    //you'll probably have to add more t helper functions here
#endif
如果您想确定您的代码总是
\u UNICODE
(我就是这么做的),请显式调用
MethodW()
,而不是
Method()
。(也有相应的
MethodA()
,但没有太多理由调用它)


还有一个
UNICODE
宏,但它应该始终与
\u UNICODE
宏相同。(不要自己定义它们,它们属于项目选项)

您需要使用C运行时库函数
strcmp
比较ANSI字符串,
wcscmp
比较UNICODE字符串

您可以这样使用它:

bool match = wcscmp(strPermission, L"0") == 0;

LPCTSTR要么是
const char*
要么是
const wchar\u t*
,所以请考虑一下。另外,您不应该检查NULL或NULL终止符,而不是字符串文字“0”吗?您可以使用C样式的字符串比较函数,但使用TCHAR的版本,即.Oops,我的意思是
\u tcscmp
,如果您尝试了第一个,但有些失望。Close可能重复,但这些数据类型更具体一些。这是这里的主要问题。问题是,虽然你可以假设LPCTSTR是一个LPCWSTR,因为问题中的L“0”,但从技术上讲,它是一个
常量TCHAR*
。@chris:从技术上讲,它是,但我忽略了这一点。我将添加一条评论。
#ifdef _UNICODE
    typedef std::string std::tstring 
    //you'll probably have to add more t helper functions here
#else
    typedef std::string std::wstring
    //you'll probably have to add more t helper functions here
#endif
bool match = wcscmp(strPermission, L"0") == 0;