开发者

Validate string within short range

I have a short integer in a string. For Eg: "123456". Is there any AP开发者_StackOverflow社区I to check whether the string contains a valid number in the range of unsigned short?

Thanks!


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.)


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";
  }
}


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜