I'm working on a BMI calculator. I want to have the user enter their height and weight in the window and use that to calculate their BMI. So far, I'm using sf::Event::TextEntered, but I don't want the user to be able to enter characters only integers. I'm pretty new to SFML, so I don't know of any way this could be done, couldn't really find anything looking through the doc. Thanks.
#include <SFML/Graphics.hpp>
class BMICalculator {
private:
sf::RenderWindow window;
sf::Font font;
sf::Text heightText;
sf::Text weightText;
sf::Text inputHeight;
sf::Text inputWeight;
sf::Event event;
std::string str;
public:
void loadWindow();
bool loadFont();
void setText();
void runProgram();
void inputData();
};
void BMICalculator::loadWindow(){
const int HEIGHT = 450;
const int WIDTH = 350;
window.create(sf::VideoMode(WIDTH, HEIGHT), "BMI Calculator");
}
bool BMICalculator::loadFont(){
return (font.loadFromFile("FreeMonoOblique.ttf"));
}
void BMICalculator::setText(){
//Input height message
heightText.setFont(font);
heightText.setCharacterSize(30);
heightText.setPosition(10, 10);
heightText.setString ("Enter Height:");
//Input weight message
weightText.setFont(font);
weightText.setCharacterSize(30);
weightText.setPosition(10, 150);
weightText.setString ("Enter Weight:");
//height entered
inputHeight.setFont(font);
inputHeight.setCharacterSize(30);
inputHeight.setPosition(10, 50);
}
void BMICalculator::inputData(){
if(event.type == sf::Event::TextEntered){
if(event.text.unicode < 128){
str += static_cast<char>(event.text.unicode);
}
}
}
void BMICalculator::runProgram(){
while (window.isOpen()){
while (window.pollEvent(event)){
if (event.type == sf::Event::Closed){
window.close();
}
inputData();
}
inputHeight.setString(str);
window.clear();
window.draw(heightText);
window.draw(weightText);
window.draw(inputHeight);
window.display();
}
}
int main(){
BMICalculator bmi;
bmi.loadWindow();
if(!bmi.loadFont())
return EXIT_FAILURE;
bmi.setText();
bmi.runProgram();
return EXIT_SUCCESS;
}