You are here:

C++/validating numeric only

Advertisement


Question
Hi Ralph,

Is there any alternative way to validate an input whether it is numeric or not? I tried to use isdigit(), but it shows that 123abc is true, and -123 is false. the input is not from cin, it is read from the command line. i'm asked to make a cpp program to calculate something like:
- task.exe 50 -3 (the operation wll be 5 * -3, which the result will be -150)
- task.exe 50 3ab (it will show an error)

please help, thank you.

Answer
Yes. Many.


----------------------------------------------------------------------------------------------------------------
   Note:   I am going to assume you are using a reasonably ISO standard C++
           language and library implementation.
           This is reasonable; the ISO C++ standard was published about 10 years
           ago so most C++ implementations should be fairly compliant by now.
----------------------------------------------------------------------------------------------------------------


First I would advise you to go and read the small print of isdigit - it works with characters not strings (C-strings as in argv[] entries nor C++ std::string objects).

Another point about isdigit is that it checks for _just_ that - whether a character is a digit, not a valid number. Digit characters would normally be the set of character values: ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9'].

A better way would be to convert them using IOStreams - as we might if using std::cin or reading from a file where we can check if the conversion worked by checking the stream state after the read. However in this case we will be reading from a string using a std::istringstream which reads input from a std::string.

We could use a std::istrstream object instead, which in this case is possible a more obvious choice as it works with char * (i.e. character arrays). However std::istrstream and std::osstrstream are listed as compatibility features in the ISO C++ standard for backwards compatibility with pre-standard C++ library implementations and code using them. They are documented as "deprecated features" and the standard goes on to say

       "where deprecated is defined as: Normative for the current edition of the
        Standard, but not guaranteed to be part of the Standard in future revisions."

(the term "Normative" means it has to be included in ISO standard C++ compliant C++ implementations)

To use a std::istringstream we create an object of that type passing it the string to use as input. If we pass a C-style zero terminated array of char then it will be converted to a std::string. We have to include <sstream>. Thus we could write:

   #include <sstream>    // for std::istringstream

   // ...

   std::istringstream  iStrStrm( argv[1] );

We then using it like so:

   #include <iostream>
   #include <sstream>    // for std::istringstream
   
   int main( int argc, char * argv[] )
   {
       if ( argc < 2 )
       {
         std::cerr << "Error: require at least one numeric command line argument."
                   << std::endl;
         return 1;
       }

       std::istringstream  iStrStrm( argv[1] );

       int n(0);
       iStrStrm >> n;

       std::cout << "n=" << n
                 << "\nstd::cin "
                 ;
       if ( iStrStrm.good() )
       {
           std::cout << "is good\n";
       }
       else
       {
           if ( iStrStrm.bad() )
           {
               std::cout << "is fatally bad ";
           }
           else if ( iStrStrm.fail() )
           {
               std::cout << "has formatting failure ";
           }
           if ( iStrStrm.eof() )
           {
               std::cout << "is at EOF ";
           }
           std::cout << std::endl;
       }
       
       return 0;   
   }

Now if we build and run it we should see something like the following:

For:

   theProgram 1000

The output should be something like:

   n=1000
   std::cin is at EOF

For:

   theProgram -1000

The output should be something like:

   n=-1000
   std::cin is at EOF

For:

   theProgram abcd

The output should be something like:

   n=0
   std::cin has formatting failure
   
And for the tricky case you sight:

   theProgram 3ab

The output should be something like:

   n=3
   std::cin is good


You will note that for fully valid arguments we not only have no failure of format conversion (iStrStrm.fail() is false) but also that the end of file flag is set (iStrStrm.eof() is true). This is because there is no whitespace around command line arguments so for a fully valid numeric argument the stream will consume and convert all the characters in the argument string and then find the end of the string and interpret it to be the end of file condition.

For the two bad cases either the fail bit is set (iStrStrm.fail() is true) or the EOF bit is not set (iStrStrm.eof() is false) indicating that there were un-processed characters in the argument string.

I hope the above example program will help you form the basis of a solution for your problem. There are other ways to do this sort of thing but the above method seems the most obvious to me!  

C++

All Answers


Answers by Expert:


Ask Experts

Volunteer


Ralph McArdell

Expertise

I am a software developer with more than 15 years C++ experience and over 25 years experience developing a wide variety of applications for Windows NT/2000/XP, UNIX, Linux and other platforms. I can help with basic to advanced C++, C (although I do not write just-C much if at all these days so maybe ask in the C section about purely C matters), software development and many platform specific and system development problems.

Experience

My career started in the mid 1980s working as a batch process operator for the now defunct Inner London Education Authority, working on Prime mini computers. I then moved into the role of Programmer / Analyst, also on the Primes, then into technical support and finally into the micro computing section, using a variety of 16 and 8 bit machines. Following the demise of the ILEA I worked for a small company, now gone, called Hodos. I worked on a part task train simulator using C and the Intel DVI (Digital Video Interactive) - the hardware based predecessor to Indeo. Other projects included a CGI based train simulator (different goals to the first), and various other projects in C and Visual Basic (er, version 1 that is). When Hodos went into receivership I went freelance and finally managed to start working in C++. I initially had contracts working on train simulators (surprise) and multimedia - I worked on many of the Dorling Kindersley CD-ROM titles and wrote the screensaver games for the Wallace and Gromit Cracking Animator CD. My more recent contracts have been more traditionally IT based, working predominately in C++ on MS Windows NT, 2000. XP, Linux and UN*X. These projects have had wide ranging additional skill sets including system analysis and design, databases and SQL in various guises, C#, client server and remoting, cross porting applications between platforms and various client development processes. I have an interest in the development of the C++ core language and libraries and try to keep up with at least some of the papers on the ISO C++ Standard Committee site at http://www.open-std.org/jtc1/sc22/wg21/.

Education/Credentials

©2012 About.com, a part of The New York Times Company. All rights reserved.