1

I am making a C (not C++) game where you have to guess the number. It uses GetWindowText() to get the text from the edit control and then check it against a fixed value of "98". If it is 98, a message box is supposed to go on screen that says "Correct!" and it closes the application. Or else, it will display a message box saying "Incorrect, try again", but should not close the window. That is where my problem is.

Every time, it displays the incorrect message, even when it is correct. Am I missing an equals() method or something?

I have tried showing the output of the second argument of GetWindowText(), and it displays what I typed. I am good with that part, but when it comes to validation, I cannot make it work.

My code:

void ValidateInput(HWND textBox)
{
    TCHAR buffer[15];

    GetWindowText(textBox, buffer, GetWindowTextLength(textBox) + 1);

    if (buffer == _T("98"))
    {
        MessageBox(null, L"Correct!", L"Guessing Game (C (Desktop))", MB_ICONASTERISK);
        DestroyWindow(hWnd);
    }
    else
    {
        MessageBox(null, L"Incorrect, try again", L"Guessing Game (C (Desktop))", MB_ICONWARNING);
    }
}

My text box (if needed)

userInputTextBox = CreateWindow(L"Edit", L"", dwUserInputTextBoxStyle, 110, 28, 50, 20, hWnd, null, hInst, null);

EDIT: strcmp works, but only a bit. I mean, if it is 97 or 99, it says correct also.

EDIT 2: Fixed.
I fixed by changing from GetWindowTextW to GetWindowTextA and using a char value. I had figured that strcmp() couldn't handle TCHARs. So then, it worked perfectly.

Working Code

void ValidateInput(HWND textBox)
{
    char buffer[10];

    GetWindowTextA(textBox, buffer, 10);

    if (strcmp(buffer, "98") == 0)
    {
        MessageBox(null, L"Correct!", L"Guessing Game (C (Desktop))", MB_ICONASTERISK);
        DestroyWindow(hWnd);
    }
    else
    {
        MessageBox(null, L"Incorrect, try again", L"Guessing Game (C (Desktop))", MB_ICONWARNING);
    }
}
  • Use `strcmp` not `==` – kaylum Feb 20 '22 at 20:32
  • @kaylum I tried, but if it gets to 97 or 99, it says correct also. I want it to only say correct to 98 – TheWaterWave222 Feb 20 '22 at 20:37
  • @kaylum: As pointed out in the edit of the question, `strcmp` will not work with [UTF-16](https://en.wikipedia.org/wiki/UTF-16) strings. – Andreas Wenzel Feb 20 '22 at 21:42
  • @MadhavBalakrishnanNair: It should not be necessary to use `GetWindowTextA` instead of `GetWindowText`, if you use [`_tcscmp`](https://learn.microsoft.com/en-us/cpp/c-runtime-library/reference/strcmp-wcscmp-mbscmp?view=msvc-170) instead of `strcmp`. The macro `_tcscmp` will expand to `wcscmp`, `_mbscmp` or `strcmp`, depending on whether `_UNICODE` or `_MBCS` is defined. Therefore, using `_tcscmp` should automatically map to the correct function for you. See the link for further information. – Andreas Wenzel Feb 21 '22 at 23:23

0 Answers0