在短范围内验证字符串
Validate string within short range
字符串中有一个短整数。例如:"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"参数。然后您可以将其转换为短格式并检查是否相等。
相关文章:
- 输入验证以筛选出字符、字符串和一系列整数
- 如何编写将验证以下字符串的正则表达式?
- 如何正确实现 std::all_of 函数来验证字符串的一部分?
- 获取线函数未定义错误。无法在字符串中保存可验证的内容
- 如何对字符串变量应用验证,使其仅接受来自用户的字母数据?
- C 未验证字符串输入
- 如何验证用户将字符串输入到std :: cin中
- 在C++测试家庭作业问题中的字符串输入时无法退出循环(作为数据验证)
- 如何使用数组字符串进行输入验证
- 如何使用 msgfmt 验证格式字符串中的位置表示法占位符
- C 验证字符串2中是否存在字符串1
- 转换和验证字符串
- 字符串验证函数出错
- 验证字符串中是否存在无效字符
- 验证C 中的两个字符串是否相等
- 输入验证,需要数字,而不是字符串.代码导致无限循环
- std::vector中的字符串验证
- if字符串验证循环出现问题
- 我如何让字符串验证仅命中的 ENTER 键
- 没有外部库的c++输入字符串验证