0
votes

I have a short integer in a string. For Eg: "123456". Is there any API to check whether the string contains a valid number in the range of unsigned short?

Thanks!

3
The by far easiest way to check if a number is in a range should be converting it into an integer (a sufficently large integer type, e.g. long) and using the comparision operators... - user395760
You mean other than errno=0; strtoul( str, 0, 10 ) <= USHRT_MAX && !errno? - Marc Mutz - mmutz

3 Answers

3
votes

Simply use the stream operators to input the number:

istringstream istr("12346");
short s;
if ((istr >> s) and istr.eof())
    cout << "valid: " << s << endl;
else
    cout << "invalid" << endl;

(Needs the header sstream.)

1
votes

I'm fond of boost::lexical_cast :

#include <boost/lexical_cast.hpp>
#include <iostream>
#include <string>

int main() {
  std::string s("12346");
  try {
    boost::lexical_cast<unsigned short>(s);
    std::cout << "valid\n";
  } catch (boost::bad_lexical_cast&) {
    std::cout << "invalid\n";
  }
}
0
votes

I would use strtol to both convert the number and to check if it was a valid number string, using the "endptr" parameter. Then you could convert it to a short and check for equality.