Welcome, Guest. Please login or register. Did you miss your activation email?

Author Topic: Switch case behaving weirdly  (Read 869 times)

0 Members and 1 Guest are viewing this topic.

MassterSheepX249

  • Newbie
  • *
  • Posts: 1
    • View Profile
    • Email
Switch case behaving weirdly
« on: September 24, 2023, 12:20:15 am »
I have this peice of code:

**BEGIN CODE HERE**

#include "SFML/Graphics.hpp"
#include <iostream>
int main()
{
        sf::RenderWindow window(sf::VideoMode(600, 600), "My window");
        sf::Event myEvent;

        while (window.isOpen())
        {
                while (window.pollEvent(myEvent))
                {
                        switch (myEvent.type)
                        {
                        case sf::Event::TextEntered:
                                std::cout << static_cast<char>(myEvent.text.unicode);
                                std::cout << "pollEventBroken";
                                break;
                        case sf::Event::KeyPressed:
                                if (myEvent.key.code == sf::Keyboard::E)
                                {
                                        std::cout << &#39;\n&#39;;
                                        break;

                                }
                        }
                }
        }
}
**END CODE HERE**

my question is why is it that when I press the key "e", the first and the second cases run instead of only the first one being run and the loop being broken?
« Last Edit: September 26, 2023, 07:58:14 am by eXpl0it3r »

kojack

  • Sr. Member
  • ****
  • Posts: 343
  • C++/C# game dev teacher.
    • View Profile
Re: Switch case behaving weirdly
« Reply #1 on: September 24, 2023, 06:44:41 am »
Technically only one case of the switch is running at a time, there's actually two events.

When you press a key like E, there's two events: a text entered event containing 101 or 69 (the unicode for "e" or "E" (depending on shift) and a key down event for the scan code 4 (the e key).
Not all keys generate textentered events, only ones with text equivalents. So not special keys.

This is how windows does it. Windows sends both a WM_CHAR and WM_KEYDOWN for keys like E, SFML turns them into Event::TextEntered and Event::KeyPressed.

Hapax

  • Hero Member
  • *****
  • Posts: 3379
  • My number of posts is shown in hexadecimal.
    • View Profile
    • Links
Re: Switch case behaving weirdly
« Reply #2 on: September 25, 2023, 12:52:02 pm »
From a usability view, you should likely not be checking to see if a key is pressed if you expect it would be processed as a TextEntered event as you wouldn't want a user to be typing something and then one of the letters did something else ;D
Selba Ward -SFML drawables
Cheese Map -Drawable Layered Tile Map
Kairos -Timing Library
Grambol
 *Hapaxia Links*

 

anything