From: roger tunnicliffe
Sent: 05 October 2022 23:40
To: fltk.general
Subject: [fltk.general] Why do I need to convert a string to a string for Fl_Input
I have the following definitions:-
Fl_Input *win2_unitprice;
win2_unitprice = new Fl_Input(x+50,y+200,100,20,"Unit Price..:");
and the following code:-
double z;
.
string s1 = to_string(z);
string s2 = s1.c_str();
// win2_unitprice->value(s1);
win2_unitprice->value(s1.c_str());
If I uncomment line 3 I get the following error:-
error: no matching function for call to ‘Fl_Input::value(std::__cxx11::string&)’
win2_unitprice->value(s1);
but if i look at the data I see that:-
s1 holds the address of the data 0x31 0x2e 0x31 0x30 ....
s2 holds the address of the data 0x31 0x2e 0x31 0x30 ....
so why do I need to use c_str() to make this work ??
<START>
Hi Roger,
The short answer is the difference between strings in C and C++ languages. A C-string has type char* - that is a pointer to a series of 8-bit characters in memory, ended with the NUL (x00) character. A C++-string (type string) is a class with some overheads to manage access to it and memory allocation.
FLTK generally uses char* to pass string data around.
The class string method string::c_str() accesses the raw char* string within the class and this is used to pass the string content to FLTK widgets.
The statement
string s2 = s1.c_str()
uses a feature of C++ that overloads the assignment operator (=) so that you can create a new C++ string from the C string.
Regards Phil.