c++gtkgtkmm

How do I read floating point numbers from file when using gtkmm?


I'm trying to write a gtkmm frontend for a project; it's my first time working with GUI. It seems that reading floating point numbers from files is problematic: I either only get to read the integer part or just some nonsense.

Here's an example I wrote to demonstrate my issue:

#include <fstream>
#include <gtkmm.h>
#include <iostream>

struct C {
  C(const char *s) {
    std::fstream f(s);

    double d;
    f >> d;
    std::cout << d << std::endl;
    f >> d;
    std::cout << d << std::endl;
  }
};

class MyWindow : public Gtk::Window {
  C c;

public:
  MyWindow();
};

MyWindow::MyWindow() : c{"input"} {
  set_title("Basic application");
  set_default_size(200, 200);
}

int main(int argc, char *argv[]) {
  C c("input");

  auto app = Gtk::Application::create("org.gtkmm.examples.base");

  return app->make_window_and_run<MyWindow>(argc, argv);
}

I compile using

g++ main.cpp `pkg-config --cflags --libs gtkmm-4.0` -std=c++17

With this input:

1.2345
6.7890

I then get

1.2345
6.789
1
0

How can I fix it or maybe find a way to transfer data structures to GTK window and then to a drawing area (which I also need)?


Solution

  • What fixed the problem for me was adding this line:

    class C {
    public:
        C(const std::string& filename) {
            std::locale::global(std::locale("C"));
            std::fstream f(filename);
            double d;
            f >> d;
            std::cout << d;
            f >> d;
            std::cout << d;
        }
    }
    

    I suspect that gtk might be modifiying locale itself after the application is launched so I have to correct it.