Search code examples
c++stringinputkeyboardsfml

How can I add a sort of text box in SFML using keyboard input and sf::Text to display the string of text?


What I am trying to do is to check if text has been entered, then add that text to the end of a string. My current code:

#include <SFML/Graphics.hpp>

int main(){
sf::RenderWindow window(sf::VideoMode(800,600),"Window", 
sf::Style::Titlebar | sf::Style::Close);
sf::Font arial;
arial.loadFromFile("arial.ttf");
sf::Text t;
t.setFillColor(sf::Color::White);
t.setFont(arial);
std::string s = "This is text that you type: ";
t.setString(s);

while(window.isOpen()){
    sf::Event event;

    while(window.pollEvent(event)){
        if(event.type == sf::Event::Closed){
            window.close();
        }
        if(event.type == sf::Event::TextEntered){
            s.append(std::to_string(event.key.code));
        }
    }
    t.setString(s);
    window.clear(sf::Color::Black);
    window.draw(t);
    window.display();
}
}

This works perfectly until I typed keys and all that was displayed was a series of numbers (the ASCII values of the keys). How would I make my program so that it appended a the key's char value to s instead of the ASCII value?

I hope I have provided enough information for you to help me. Any replies are appreciated :)


Solution

  • Documentation is your friend :-) In the event of a TextEntered event, event.text "contains the Unicode value of the entered character. You can either put it directly in a sf::String, or cast it to a char after making sure that it is in the ASCII range (0 - 127)."

    There's no mention of the event.key member for the TextEntered event, which is intended for the KeyPressed event. The "ASCII values" you're seeing are probably garbage values due to the key member of the union being inactive and overwritten with other data. Also note that std::to_string only converts numbers to their decimal representation.

    Here's some code that should work for you:

    if (event.type == sf::Event::TextEntered){
        if (event.text.unicode < 128){
            s += static_cast<char>(event.text.unicode);
        } else {
            // Time to consider sf::String or some other unicode-capable string
        }
    }