如何在 c++ 中解析包含整数的字符串并检查是否大于最大值
How to parse a string containing an integer and check if greater than a maximum in c++
我想确定(在 c++ 中(字符串是否包含 0 - UINT_MAX范围内的数字 我已经尝试过 atoi 等,但这不能处理这种情况。 例如,字符串42949672963将无法通过测试 有人有什么建议吗?
您可以使用标准的C++函数std::strtoul
然后检查转换后的数字是否不大于std::numeric_limits<unsigned int>::max()
。
例如
#include <iostream>
#include <string>
#include <stdexcept>
#include <limits>
int main()
{
std::string s( "42949672963" );
unsigned int n = 0;
try
{
unsigned long tmp = std::stoul( s );
if ( std::numeric_limits<unsigned int>::max() < tmp )
{
throw std::out_of_range( "Too big number!" );
}
n = tmp;
}
catch ( const std::out_of_range &e )
{
std::cout << e.what() << 'n';
}
std::cout << "n = " << n << 'n';
return 0;
}
程序输出为
Too big number!
n = 0
您还可以为无效数字表示形式再添加一个捕获。
另一种方法是使用标准 C 函数strtoul
如果您不想处理异常。
现代方法是使用 std::stoi, std::stoll 等
字符串和字符串有重载,可以处理较大的尺寸。
https://en.cppreference.com/w/cpp/string/basic_string/stol
您可以在循环中逐个字符搜索字符串,每次出现连续数字时,您都可以建立一个整数,同时检查Max UINT。
相关文章:
- 获取字符串的长度并将其分配给数组
- 将字符指针十六进制转换为字符串并保存在文本文件C++中
- 如何打开并写入一个名称取自C++中字符串的文件
- 调用CreateProcess()并获取字符串的返回值
- 找到具有最多子串栅栏的字符串排列
- 从字符串中提取整数并形成一个数组
- 在 C++11 中,如何查找并返回以给定字符串开头的字符串向量中的所有项?
- 将字符串拆分为标记,并将标记拆分为两个单独的数组
- 接收字符串并使用它来调用方法C++
- 如何从文件中读取两个字符串和数字数组,并将它们存储在对象向量中
- 当分配一个字符串值并稍后通过分配另一个值进行更改时C++如何管理内存?
- 将 S1 转换为回文,并将 S2 作为其子字符串
- 如何分隔字符串并将标记传递给方法
- 使用字符串流读取整数并将它们相加
- 如何在不知道对应关系的情况下在字符串中搜索字符并将其分配给另一个字符?
- 如何从字符串向量构造对象并避免复制?
- std::regex:匹配由数字和空格组成的字符串,并提取数字.如何?
- 用Osttream语法双串到字符串
- 将标准字符串转换为 ascii 字符并通过串行端口 c++ 发送
- 从Arduino到处理的完整串行字符串