Odd behaviour in KeyPress:getTextCharacter


Using this method, I would expect “a” to be returned if the a key was pressed. However, it’s returning the ascii code, 97.

Any thoughts? Thank you.

On that level the machine doesn’t know the difference. The returned wchar is just up to 4 bytes, so a number in either way. But if you send it to a terminal, it would be printed as the character. Sure, it might depend on which command or format options you choose…

Does that help?

It helps in understanding. For a practical solution to what I’m trying to achieve, what’s then the best way to convert a String to a format to compare? I would have though it would have been easiest for KeyPress to have a method to return a String, but as I’m still early on in coding, there’s probably a very good reason I don’t know!


To compare you can do this:

juce_wchar c = KeyPress::getTextCharacter();
if (c == 'a') DBG ("'a' was pressed");
if (c == 97)  DBG ("...as I said, 'a' was pressed");

// you can also use it in switch IIRC
switch (KeyPress::getTextCharacter()) {
    case 'a':
        DBG ("'a' was pressed");

// The lazy way to create a string:
String text (&c, 1);

But if you use this String constructor, you must specify a length, because it is not a 0-terminated string, so this constructor would read random memory leading to undefined behaviour.
String::charToString() that you already found is the better solution to create a String.

Thank you Daniel for your very detailed response! charToString() was the best solution as I needed to convert to String anyway as it was comparing with the Strings from a ComboBox.