文書の過去の版を表示しています。


サンプルアプリケーション: BMI計算機

FLTK

BMI計算機

#include <FL/Fl.H>
#include <FL/Fl_Input.H>
#include <FL/Fl_Output.H>
#include <FL/Fl_Return_Button.H>
#include <FL/Fl_Window.H>

#include <cstdlib>
#include <optional>

Fl_Input *height_input;
Fl_Input *weight_input;
Fl_Output *result_output;

std::optional<double> double_value(Fl_Input const *input) {
  char const *value_str = input->value();
  if (*value_str == '\0') {
    return {};  // Empty string is not accetable
  }

  char *end_str = nullptr;
  errno = 0;

  // NOTE: We also can use std::stod with std::string instead of std::strtod.

  if (double value = std::strtod(value_str, &end_str);
      *end_str == '\0' && errno == 0) {
    return value;  // Successfully converted to double value
  }
  return {};  // Invalid format
}

void calc_button_cb(Fl_Widget *w, void *data) {
  auto h_cm = double_value(height_input);
  auto w_kg = double_value(weight_input);

  if (h_cm.has_value() && w_kg.has_value()) {
    double h_m = *h_cm / 100;
    double bmi = *w_kg / (h_m * h_m);
    result_output->value(bmi);
    result_output->textcolor(FL_FOREGROUND_COLOR);
  } else {
    result_output->value("Invalid input.");
    result_output->textcolor(FL_RED);
  }
}

int main(int argc, char **argv) {
  auto window = new Fl_Window(230, 160, "BMI Calculator");
  height_input = new Fl_Input(100, 10, 100, 30, "Height (cm)");
  weight_input = new Fl_Input(100, 40, 100, 30, "Weight (kg)");
  auto calc_button = new Fl_Return_Button(20, 80, 180, 30, "Calculate");
  result_output = new Fl_Output(100, 120, 100, 30, "BMI");

  calc_button->callback(calc_button_cb);

  window->end();
  window->show(argc, argv);
  return Fl::run();
}

文書の編集
文書の先頭へ