contrib/mul/mbl/mbl_read_int.cxx
Go to the documentation of this file.
00001 // This is mul/mbl/mbl_read_int.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, updated by me apparently!!!
00009 //  updated to vxl caringly in the way one can only do on a Friday afternoon by gvw
00010 //
00011 // - Function Name: mbl_read_int
00012 // - Synopsis:      int mbl_read_int(char* q_str, int default_int)
00013 // - Inputs:        q_str: A question
00014 //                  default_int: Default answer
00015 //                  min_int: Min allowed value (optional)
00016 //                  max_int: 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 an integer, 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 //    int new_scale = mbl_read_int("Scale?",5);
00028 //    int new_scale = mbl_read_int("Scale?",5,min_scale,max_scale);
00029 // \endcode
00030 
00031 #include "mbl_read_int.h"
00032 #include <vcl_cstdio.h> // for fgets()
00033 #include <vcl_iostream.h>
00034 
00035 const int MAX_LEN = 20;
00036 
00037 // If min_int != 0 or max_int != 0 then prints range but doesn't check that reply is in range
00038 int RD_ReadInt1(const char* q_str, int default_int,
00039                 int min_int, int max_int)
00040 {
00041   char reply[MAX_LEN];
00042 
00043   while (true)
00044   {
00045     if (min_int==0 && max_int==0)
00046       vcl_cout<<q_str<<" ("<<default_int<<") :";
00047     else
00048       vcl_cout<<q_str<<" ["<<min_int<<".."<<max_int<<"] ("<<default_int<<") :";
00049     vcl_cout.flush();
00050 
00051     if (vcl_fgets(reply,MAX_LEN,stdin)!=NULL)
00052     {
00053       int r = default_int;
00054       if (reply[0]=='\n' || vcl_sscanf(reply,"%d",&r)>0)
00055         return r;
00056     }
00057   }
00058 }
00059 
00060 int mbl_read_int(const char* q_str, int default_int)
00061 {
00062   return RD_ReadInt1(q_str,default_int,0,0);
00063 }
00064 
00065 int mbl_read_int(const char* q_str, int default_int,
00066                  int min_int, int max_int)
00067 {
00068   while (true)
00069   {
00070     int R = RD_ReadInt1(q_str,default_int,min_int,max_int);
00071     if (R<min_int)
00072       vcl_cout<<R<<": must be at least "<<min_int<<"\n";
00073     else if (R>max_int)
00074       vcl_cout<<R<<": must be no more than "<<max_int<<"\n";
00075     else
00076       return R; // acceptable
00077   }
00078 }