将字符串转换为无符号整数会返回错误的结果 [英] Converting string to unsigned int returns the wrong result

查看:25
本文介绍了将字符串转换为无符号整数会返回错误的结果的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下字符串:

sThis = "2154910440";

unsigned int iStart=atoi(sThis.c_str());

结果是

iStart = 2147483647

有人看到我的错误吗?

推荐答案

atoi 将字符串转换为 int.在您的系统上,int 是 32 位,其最大值为 2147483647.您尝试转换的值不在此范围内,因此 atoi 的返回值是不明确的.我猜你的实现在这种情况下返回 int 的最大值.

atoi converts a string to an int. On your system, an int is 32 bits, and its max value is 2147483647. The value you are trying to convert falls outside this range, so the return value of atoi is undefined. Your implementation, I guess, returns the max value of an int in this case.

您可以改为使用 atoll,它返回一个长long,保证至少为 64 位.或者您可以使用 stoi/stol/stoll 中的函数族,或者他们的无符号对应项,它们实际上会提供有关超出范围值的有用错误报告(和无效值)以异常的形式.

You could instead use atoll, which returns a long long, which is guaranteed to be at least 64 bits. Or you could use a function from the stoi/stol/stoll family, or their unsigned counterparts, which will actually give useful error reports on out of range values (and invalid values) in the form of exceptions.

就个人而言,我喜欢 boost::lexical_cast.尽管它看起来有点麻烦,但它可以在更一般的上下文中使用.您可以在模板中使用它,只需转发类型参数,而不必专门化

Personally, I like boost::lexical_cast. Even though it appears a bit cumbersome, it can be used in a more general context. You can use it in templates and just forward the type argument instead of having to have specializations

这篇关于将字符串转换为无符号整数会返回错误的结果的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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