One keyboard event creates two events in the program

See the code example below. Both the ‘if sflag’ statement and the ‘else’ statement get executed for a single hit of the s-key. The output of the printf() statements is visible after the program times out and ends (about 10 seconds) - the terminal screen is then displayed. It seems like the key hit generates a program event for each of the down and up strokes - though I specified the KEY_DOWN event only. How do I code it to generate only the key down event.? Thanks.

Code:

#include <SDL2/SDL.h>
#include <stdio.h>

int main(){

int sflag=1, lcount=0;

SDL_Init(SDL_INIT_VIDEO);
SDL_DisplayMode vmode;
SDL_GetDisplayMode(0, 0, &vmode);
SDL_Window win1 = NULL;
win1=SDL_CreateWindow(“graf”,0,0,vmode.w,vmode.h,SDL_WINDOW_SHOWN);
SDL_Renderer
ren = NULL;
ren = SDL_CreateRenderer( win1, 0, SDL_RENDERER_ACCELERATED);
SDL_SetRenderDrawColor( ren, 0, 0, 0, 255 );
SDL_RenderClear( ren );
SDL_Event event;

while(1)
{ if(SDL_PollEvent(&event) != 0 ) //SDL_PE = 1 if key hit
{ const Uint8 *state = SDL_GetKeyboardState(NULL);
const Uint8 *type = SDL_GetKeyboardState(NULL);

	if (state[SDL_SCANCODE_S] && type[SDL_KEYDOWN])
	{	
		if (sflag==1)				
		{	
			sflag=0;
			printf("transition from 1 to 0\n");
		}
		else
		{	
			sflag=1;
			printf("transition from 0 to 1\n");
		}
	}
}

// SDL_SetRenderDrawColor(ren,255,0,144,255);
// SDL_RenderDrawPoint(ren,10,10); //plot one pixel
// SDL_RenderPresent(ren);

SDL_Delay(10);
lcount++;
if (lcount == 1000)
goto x100;

}

x100:;
SDL_DestroyRenderer(ren);
SDL_DestroyWindow(win1);
SDL_Quit();
return 0;
}

These lines are clearly incorrect. If you want to check for event type,
you’re going to look at the actual event object. The second line should
look something like this:

if (e.type == SDL_KEYDOWN && e.key.keysym.scancode == SDL_SCANCODE_S)

…and the first line shouldn’t exist at all.On 10.06.2016 08:11, bilsch01 wrote:

  const Uint8 *type  = SDL_GetKeyboardState(NULL);

  if (state[SDL_SCANCODE_S] && type[SDL_KEYDOWN])


Rainer Deyke (rainerd at eldwood.com)

…where ‘e’ is the event object, which you called ‘event’, so the
actual code would be:

if (event.type == SDL_KEYDOWN
&& event.key.keysym.scancode == SDL_SCANCODE_S)On 10.06.2016 13:26, Rainer Deyke wrote:

if (e.type == SDL_KEYDOWN && e.key.keysym.scancode == SDL_SCANCODE_S)


Rainer Deyke (rainerd at eldwood.com)