Programming In C and Win32 API: Comparing Strings
I am writing a program in C and Windows API. I am using Vis开发者_如何学Goual Studio 2010 Express and Character Set is set to "Not Set". I have made an edit control to accept username. Here's declaration:
hwnduser = CreateWindow (TEXT("EDIT"), NULL,
WS_VISIBLE | WS_CHILD | WS_BORDER,
220, 70, 80, 20,
hwnd, (HMENU) 3, NULL, NULL);
I am fetching its value into a string named username.
len = GetWindowTextLength(hwnduser) + 1;
GetWindowText(hwnduser, username, len);
Now, the valid username is in a string called c_user:
char c_user[] = "foo";
When I compare them to check if the user has entered valid username using following code,
if (username == c_user)
{
MessageBox(hwnd, "Foo", "Bar", MB_OK);
}
else
{
MessageBox(hwnd, "Bar", "Foo", MB_OK);
}
It never validates. Instead, the else condition is always executed! Where am I making a mistake?
How to correct this?
I have tried strcmp! But still, output does not change. See the output(and comparison in code):
C and C++ have no built-in string type and so you cannot compare strings this way. C and C++ instead use an array of chars and this syntax simply compares the address of each array (which won't match).
Instead use strcmp()
or _tcscmp()
.
I believe you'll actually need to use wchar_t's (wide characters). it's been a while since I've looked at the syntax but i think it'll be something like this:
wchar_t* c_user = L"foo";
if (wcscmp(username, c_user) == 0) ...
make sure username is also defined as the correct type.
you might also look into TCHAR which is a more generic representatic of a character type (it changes based off of the compiler settings). depending on settings, itll either be a char or wchar_t i think.
Writing username == c_user
checks whether they both point to the same memory location.
You need to call strcmp
to compare the strings' values.
I'd use strcmp (or any synonym)
if ( strcmp( username, c_user) == 0 )
{
// 0 indicate there is no difference, thus equal
}
else
{
}
You should use strcmp for this , or strcmpi if you want to ignore the case.
if (strcmp(username, c_user) == 0) { ... }
Use the functions GetWindowTextA() and MessageBoxA(), it works for me.
精彩评论