我想做的是检查是否输入了文本,然后将该文本添加到字符串的末尾。我当前的代码:
#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是你的 friend :-) 如果出现TextEntered
事件,event.text
“包含输入字符的 Unicode 值。您可以将它直接放在 sf::String
中,或者在确保它在 ASCII 范围 (0 - 127) 后将其转换为 char
。”
没有提到 event.key
TextEntered
的成员事件,用于 KeyPressed
事件。您看到的“ASCII 值”可能是垃圾值,因为 union 的关键成员处于非事件状态并被其他数据覆盖。另请注意 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
}
}
关于c++ - 如何使用键盘输入和 sf::Text 在 SFML 中添加一种文本框来显示文本字符串?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54681508/