Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cast a string from Glib::ustring to double - gtkm 2

I am developing an c++ app in gtkmm 2

I have a problem to cast the string from an entryfield to a double (or int).

I get the following compilation error

 cannot convert from Glib::ustring to double

The entryfield

 interestrate.set_max_length(50);
interestrate.set_text(interestrate.get_text() );
interestrate.select_region(0, interestrate.get_text_length());
m_box1.pack_start(interestrate);
interestrate.show();

the button

m_button3.signal_clicked().connect(sigc::bind<-1, Glib::ustring>(
    sigc::mem_fun(*this, &HelloWorld::on_button_clicked), "OK"));

m_box1.pack_start(m_button3);
m_button3.show();

and the eventhandler

 void HelloWorld::on_button_clicked(Glib::ustring data)
 {
  std::cout << "interestrate: " << interestrate.get_text() << std::endl; 
 }

so i want to get a double of the returnvalue from

 interestrate.get_text()
like image 335
user2991252 Avatar asked Dec 14 '25 13:12

user2991252


2 Answers

I didnt beleive it could be so easy

 std::string s = interestrate.get_text();
 double d = atof(s.c_str());
like image 147
user2991252 Avatar answered Dec 17 '25 01:12

user2991252


Your suggestion would work for valid C locale input.

If you want to deal with bad number formats and locale considerations you have to do a little bit more; atof returns 0 on error, but 0 may be a valid input, and here in Germany users would perhaps enter a comma as the decimal point.

I would think (from reading the glib docs and this answer: How can I convert string to double in C++?), that you should get the proper localized std::string first via Glib::locale_from_utf8() and then create a stringstream from that and read your double out of that. The stream gives you error information and the conversion/operator>>() will deal with locale issues if you have "imbued" a locale.

like image 42
Peter - Reinstate Monica Avatar answered Dec 17 '25 03:12

Peter - Reinstate Monica



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!