我有一个C++项目需要编辑.这是变量的声明:
LPSTR hwndTitleValue = (LPSTR)GlobalAlloc(GPTR,(sizeof(CHAR) * hwndTitleSize));
Run Code Online (Sandbox Code Playgroud)
如何检查此字符串是否为空?
我试过简单if(hwndTitleValue == "")但它总是返回false.如何检查此字符串是否为空?
编辑
我还需要检查文件是否已附加.这是文件的代码:
// Attachment
OFSTRUCT ofstruct;
HFILE hFile = OpenFile( mmsHandle->hTemporalFileName , &ofstruct , OF_READ );
DWORD hFileSize = GetFileSize( (HANDLE) hFile , NULL );
LPSTR hFileBuffer = (LPSTR)GlobalAlloc(GPTR, sizeof(CHAR) * hFileSize );
DWORD hFileSizeReaded = 0;
ReadFile( (HANDLE) hFile , hFileBuffer, hFileSize, &hFileSizeReaded, NULL );
CloseHandle( (HANDLE) hFile );
Run Code Online (Sandbox Code Playgroud)
如何检查是否hFile为空?
Gra*_*row 18
检查字符串是否为空的最简单方法是查看第一个字符是否为空字节:
if( hwndTitleValue != NULL && hwndTitleValue[0] == '\0' ) {
// empty
}
Run Code Online (Sandbox Code Playgroud)
您可以使用strlen或strcmp在其他答案中使用,但这会保存函数调用.
Bru*_*ant 11
我相信hwndTitleValue是一个指针,至少在匈牙利表示法中它会是.您的方法是分配一个字节数组(ANSI C字符串),因此最好的方法是
#include <string.h>
// ... other includes ...
int isEmpty(LPSTR string)
{
if (string != NULL)
{
// Use not on the result below because it returns 0 when the strings are equal,
// and we want TRUE (1).
return !strcmp(string, "");
}
return FALSE;
}
Run Code Online (Sandbox Code Playgroud)
但是,您可以破解上述方法而不使用strcmp:
#include <string.h>
// ... other includes ...
int isEmpty(LPSTR string)
{
// Using the tip from Maciej Hehl
return (string != NULL && string[0] == 0);
}
Run Code Online (Sandbox Code Playgroud)
需要注意的一点是,字符串可能不是空的,而是填充空格.此方法将告诉您字符串包含数据(空格是数据!).如果您需要考虑填充空格的字符串,则需要先修剪它.
编辑:另外需要注意的是,上面的方法没有正确地从NULL指针中解释.如果指针为null,isEmpty则返回FALSE,这是不希望的.我们可以删除NULL检查然后它成为调用者的责任,或者我们可以定义isEmpty返回FALSE为NULL字符串.
#include <string.h>
// ... other includes ...
int isEmpty(LPSTR string)
{
// Always return FALSE to NULL pointers.
if (string == NULL) return FALSE;
// Use not on the result below because it returns 0 when the strings are equal,
// and we want TRUE (1).
return !strcmp(string, "");
}
Run Code Online (Sandbox Code Playgroud)