How To Get ASCII/Char Values Of Keyboard Key Pressed?

Hi,

Updating our SDL2 2-D game engine now.
How would I get the ASCII & char values of a keyboard key pressed?
Thanks!

Jesse

You don’t, you use SDL_TEXTINPUT events for this.
Somehow I have the feeling we’ve had this talk before…

Possible…
I already did these modifications to the engine about a year ago, but did not back it up.
SDL_TEXTINPUT seems excessive to me.
I just need char pressed on keyboard for game input and new high score name input.
Thanks!

Jesse

You get the pressed char(s) from SDL_TEXTINPUT.
Just use it, it’s not hard.

Ok, I give up…

Trying SDL_TEXTINPUT now.
When there is a SDL_TEXTINPUT event, how do I get the char?

Thanks!

Jesse

Ok, have this:
case SDL_TEXTINPUT:
KeyOnKeyboardPressedByUser = Event.text.text; // Line of ERROR
break;

but it has error:
\vmware-host\Shared Folders\VM-SHARE\GT-R_Engine\src\input.cpp|826|error: invalid conversion from ‘char*’ to ‘char’ [-fpermissive]|

KeyOnKeyboardPressedByUser is a char

Jesse

event.text.text is a String that could contain up to 32 chars and is \0-terminated
Simple code that only handles ASCII could look like the following:

SDL_Event event;
while(SDL_PollEvent(&event))
{
	switch(event.type)
	{
		// ... code for handling mouse events etc
		case SDL_TEXTINPUT: // this handles text input events
			for(int i=0; i<SDL_TEXTINPUTEVENT_TEXT_SIZE; ++i)
			{
				char c = event.text.text[i];
				// cancel if a non-ascii char is encountered
				if(c < ' ' || c > '~')
					break;
				
				do_something_useful_with( c );
			}	
		
			break;
	}
}

Ok, it works, thanks!

Great!

See, it wasn’t that hard after all :slight_smile: