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

Viewed 474

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?

2 Answers

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";
    }
}

Enum fields for letters are arranged in the same way as in the ASCII. By using this property you can get a char by adding abd subtracting:

#include <SFML/Graphics.hpp>
#include <iostream>
#include <string>

int main() {
    sf::RenderWindow window(sf::VideoMode(1200, 650), "");
    std::string enteredChars;
    enteredChars.reserve(1000);

    while (window.isOpen()) {
        sf::Event event;
        while (window.pollEvent(event)) {
            if (event.type == sf::Event::Closed || event.type == sf::Event::KeyPressed && event.key.code == sf::Keyboard::Escape) {
               window.close();
            } else if (event.type == sf::Event::KeyPressed) {
                const sf::Keyboard::Key keycode = event.key.code;
                if (keycode >= sf::Keyboard::A && keycode <= sf::Keyboard::Z) {
                    char chr = static_cast<char>(keycode - sf::Keyboard::A + 'a');
                    enteredChars.push_back(chr);
                }
            }
        }

        window.clear();
        window.display();
    }

    std::cout << enteredChars << "\n";
}
Related