contrib/mul/mbl/mbl_read_double.cxx
Go to the documentation of this file.
00001 // This is mul/mbl/mbl_read_double.cxx
00002 #ifdef VCL_NEEDS_PRAGMA_INTERFACE
00003 #pragma implementation
00004 #endif
00005 //:
00006 // \file
00007 // \brief Asks question and waits for an answer
00008 // \author tim
00009 // hand crafted into vxl by gvw
00010 //
00011 // - Function Name: mbl_read_double
00012 // - Synopsis:      double mbl_read_double(char* q_str, double default_d)
00013 // - Inputs:        q_str: A question
00014 //                  default_d: Default answer
00015 //                  min_d: Min allowed value (optional)
00016 //                  max_d: Max allowed value (optional)
00017 // - Outputs:       -
00018 // - Returns:       The answer or a default
00019 // - Description:   Asks question and waits for an answer.
00020 //                  If the answer is a double, returns it.
00021 //                  If the answer is an empty vcl_string (return)
00022 //                  then returns default.
00023 //                  Otherwise waits for another input.
00024 // - References:    -
00025 // - Example:
00026 // \code
00027 //    double new_scale = mbl_read_double("Scale?",1.00);
00028 //    double new_scale = mbl_read_double("Scale?",1.00,min_scale,max_scale);
00029 // \endcode
00030 
00031 #include "mbl_read_double.h"
00032 #include <vcl_cstdio.h> // for fgets()
00033 #include <vcl_iostream.h>
00034 
00035 const int MAX_LEN = 40;
00036 
00037 // If min_d != 0 or max_d != 0 then prints range but doesn't check that reply is in range
00038 double RD_ReadDouble1(const char *q_str, double default_d,
00039                       double min_d, double max_d)
00040 {
00041   char reply[MAX_LEN];
00042 
00043   while (true)
00044   {
00045     if (min_d==0 && max_d==0)
00046       vcl_cout<<q_str<<" ("<<default_d<<") :";
00047     else
00048     vcl_cout<<q_str<<" ["<<min_d<<".."<<max_d<<"] ("<<default_d<<") :";
00049     vcl_cout.flush();
00050 
00051     if (vcl_fgets(reply,MAX_LEN,stdin)!=NULL)
00052     {
00053       double r = default_d;
00054       if (reply[0]=='\n' || vcl_sscanf(reply,"%lf",&r)>0)
00055         return r;
00056     }
00057   }
00058 }
00059 
00060 double mbl_read_double(const char *q_str, double default_d)
00061 {
00062   return RD_ReadDouble1(q_str,default_d,0,0);
00063 }
00064 
00065 double mbl_read_double( const char *q_str, double default_d,
00066                         double min_d, double max_d)
00067 {
00068   while (true)
00069   {
00070     double R = RD_ReadDouble1(q_str,default_d,min_d,max_d);
00071     if (R<min_d)
00072       vcl_cout<<R<<": must be at least "<<min_d<<"\n";
00073     else if (R>max_d)
00074       vcl_cout<<R<<": must be no more than "<<max_d<<"\n";
00075     else
00076       return R; // acceptable
00077   }
00078 }
00079