Search code examples
c++sfml

Is there an easier way have keyboard input return a char (SFML)?


I want to use the keyboard input as a parameter for a function. I'm trying to get a keyboard input that returns a char: the key pressed.

Is there a better way to do it than how I'm doing it now?

char getKey() {
    if (sf::Keyboard::isKeyPressed(sf::Keyboard::A))
    {
        return 'A';
    } 
    if (sf::Keyboard::isKeyPressed(sf::Keyboard::A))
    {
        return 'A';
    }
    if (sf::Keyboard::isKeyPressed(sf::Keyboard::B))
    {
        return 'B';
    }
    if (sf::Keyboard::isKeyPressed(sf::Keyboard::C))
    {
        return 'C';
    }

    //...

    return '\0';
}

I know you can get use TextEntered, but I don't want to get other ASCII keys(å, ∫, ç, ...)

Is there an easier way to do this without going through every letter?


Solution

  • You can just handle events in your code

    while (window.pollEvent(event)) 
    {
        if (event.type == sf::Event::Closed)
        {
            window.close();
            break;
        } 
        else if(event.type == sf::Event::KeyPressed)
        {
            const sf::Keyboard::Key keycode = event.key.code;
            if (keycode == sf::Keyboard::A) 
                std::cout << "A is pressed";
        }
    }