Crash Course C++Builder - part 4: Event HandlersOur Foot-To-Meter Convertor still doesn't do anything useful. OnClick Event Handler for btnFootToMeterIn part 3 we've put some temporary code in the event handler of btnFootToMeter. But what should this event handler really do?
We'll keep temporary values and texts in the variables Foot, Meter and ResultString. For the moment, don't worry about all the different types of variables. Later on, we shall come back to this in detail. Now, let's code!
Adding commentsNow let's add some comments to our code. Comments is very important! Today you still remember what your code means, but what when you want to modify it later on, in a month or in a year? Comments text is preceded by a double slash // and is disregarded by the compiler. Below we abundantly commented our code -- maybe we exagerated it a bit ;) //---------------------------------------------------------- // Event handler for the OnClick of btnfoottometer //---------------------------------------------------------- void __fastcall TForm1::btnFootToMeterClick(TObject *Sender) { // Variables float Foot; float Meter; string ResultString; // Show the name of the starting length unit lblStartUnit->Caption = "foot"; // Convert the text of the EDIT to a numerical value Foot = StrToFloat(edInput->Text); // Convert from foot to meter Meter = Foot * 0.3048; // Convert the floating point number to string-format. // "0.00" is the "format string", meaning: // Format the result with 2 decimal digits in the fractional part // (part to the right of the decimal separator) ResultString = FormatFloat("0.00", Meter); // Add the string " meter" and put the string in the CAPTION of the LABEL lblResult->Caption = ResultString + " meter"; } //---------------------------------------------------------- // Event handler for the OnClick event of btnMeterToFoot ////-------------------------------------------------------- void __fastcall TForm1::btnMeterToFootClick(TObject *Sender) { // Variables float Foot; float Meter; string ResultString; // Show the name of the starting length unit lblStartUnit->Caption = "meter"; // Convert the text of the EDIT to a numerical value Meter = StrToFloat(edInput->Text); // Convert from meter to foot Foot = Meter / 0.3048; // Convert the floating point number to string-format. ResultString = FormatFloat("0.00", Foot); // Add the string " foot" and put the string in the CAPTION of the LABEL lblResult->Caption = ResultString + " foot"; } |
Table of contents
1. Compiling a Project 2. Form, Edits, buttons 3. Properties and events 4. Event handlers 5. Validating the input |