如何使用键盘输入和 sf::Text 在 SFML 中添加一种文本框来显示文本字符串?

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

我想做的是检查是否输入了文本,然后将该文本添加到字符串的末尾。我当前的代码:

#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();
}
}

在我键入键之前,这一切正常,但显示的只是一系列数字(键的 ASCII 值)。我将如何制作我的程序以便将键的 char 值附加到 s 而不是 ASCII 值?

希望我提供的信息足够您帮助我。任何答复表示赞赏:)

Documentation 是你的朋友 :-) 如果发生 TextEntered 事件,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)."

没有提到 TextEntered 事件的 event.key 成员,它是为 KeyPressed 事件准备的。您看到的 "ASCII values" 可能是垃圾值,因为联合的关键成员处于非活动状态并被其他数据覆盖。另请注意,std::to_string 仅将数字转换为其 十进制 表示形式。

下面是一些适合您的代码:

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