在短范围内验证字符串

Validate string within short range

本文关键字:字符串 验证 范围内      更新时间:2023-10-16

字符串中有一个短整数。例如:"123456"。是否有任何API来检查字符串是否包含unsigned short范围内的有效数字?

谢谢!

直接使用流操作符输入数字:

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

(需要标题sstream .)

我喜欢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 << "validn";
  } catch (boost::bad_lexical_cast&) {
    std::cout << "invalidn";
  }
}

我将使用strtol来转换数字并检查它是否是一个有效的数字字符串,使用"endptr"参数。然后您可以将其转换为短格式并检查是否相等。