如何检查从C ++字符串到无符号整数的转换 [英] How to check conversion from C++ string to unsigned int

查看:139
本文介绍了如何检查从C ++字符串到无符号整数的转换的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要:

1)查找当前系统上的最大unsigned int值。我没有找到它limits.h。是否安全写 unsigned int maxUnsInt = 0 - 1; ?我也尝试了 unsigned int maxUnsInt = MAX_INT * 2 + 1 ,返回正确的值,但编译器显示一个关于int溢出操作的警告。

1) Find what is the maximum unsigned int value on my current system. I didn't find it on limits.h. Is it safe to write unsigned int maxUnsInt = 0 - 1;? I also tried unsigned int maxUnsInt = MAX_INT * 2 + 1 that returns the correct value but the compiler shows a warning about int overflow operation.

2)一旦找到,检查一个C ++字符串(我知道它只由数字组成)超过了系统上的最大unsigned int值。

2) Once found, check if a C++ string (that I know it is composed only by digits) exceeded the maximum unsigned int value on my system.

我的最终目标是使用atoi将字符串转换为unsigned int,如果且仅当它是一个有效的unsigned int。

My final objective is to convert the string to a unsigned int using atoi if and only if it is a valid unsigned int. I would prefer to use only the standard library.

推荐答案

应该有一个 #define UINT_MAX < limits.h> ;我会是
非常惊讶,如果没有。否则,保证

There should be a #define UINT_MAX in <limits.h>; I'd be very surprised if there wasn't. Otherwise, it's guaranteed that:

unsigned int u = -1;

将产生最大值。在C ++中,还可以使用
std :: numeric_limits< unsigned int> :: max(),但是直到C ++ 11,
不是一个整数常数表达式(这可能或可能
不是一个问题)。

will result in the maximum value. In C++, you can also use std::numeric_limits<unsigned int>::max(), but until C++11, that wasn't an integral constant expression (which may or may not be a problem).

unsigned int u = 2 * MAX_INT + 1;

不能保证是任何东西(至少在一个系统上,
MAX_INT == UMAX_INT )。

is not guaranteed to be anything (on at least one system, MAX_INT == UMAX_INT).

对于检查字符串,最简单的解决方案是
使用 strtoul ,然后验证 errno 和返回值:

With regards to checking a string, the simplest solution would be to use strtoul, then verify errno and the return value:

bool
isLegalUInt( std::string const& input )
{
    char const* end;
    errno = 0;
    unsigned long v = strtoul( input.c_str(), &end, 10 );
    return errno == 0 && *end == '\0' && end != input.c_str() && v <= UINT_MAX;
}

如果使用C ++ 11,还可以使用 std :: stoul ,其中
在溢出时抛出 std :: out_of_range 异常。

If you're using C++11, you could also use std::stoul, which throws an std::out_of_range exception in case of overflow.

这篇关于如何检查从C ++字符串到无符号整数的转换的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆