如何将ASCII转换为无符号整数。

12

是否有一种将字符串转换为无符号整数的方法? _ultoa函数可以将无符号长整型转换为字符串,但找不到相反的版本...

5个回答

19

2
atoi不支持无符号类型,对吧?在Windows CRT中,如果发生溢出,它会返回一个错误(ERANGE)。 - Cheeso
Cheeso,是的,根据“i”的类型推断,它应该是整数类型;-) - Michael Krelin - hacker

10
Boost提供了lexical_cast。
#include <boost/lexical_cast.hpp>
[...]
unsigned int x = boost::lexical_cast<unsigned int>(strVal);

或者,您可以使用stringstream(它基本上是在内部执行了lexical_cast的操作):

#include <sstream>
[...]
std::stringstream s(strVal);
unsigned int x;
s >> x;

1
如果您需要非十进制解释,请参考以下链接:https://dev59.com/43NA5IYBdhLWcg3wKaYx - Martin
我是唯一一个喜欢流插入但讨厌流提取的人吗?每次我都会使用函数(例如这个boost函数),尽管老实说,我可能还是会不加思考地使用atoi。 - user180247
是的,流提取相当丑陋,特别是因为你不能用它初始化常量。但它也更加强大,因为你可以使用操作符来改变你的基数等。 - Martin

1

sscanf会做你想要的事情。

char* myString = "123";  // Declare a string (c-style)
unsigned int myNumber;   // a number, where the answer will go.

sscanf(myString, "%u", &myNumber);  // Parse the String into the Number

printf("The number I got was %u\n", myNumber);  // Show the number, hopefully 123

1
即使在C语言中,我也讨厌scanf系列函数。它从来没有按照我的意愿执行,并且大多数情况下会导致错误。如果您已经使用其他代码检查或提取了字符串并知道其符合要求,那么使用atoi或其他函数就可以了,这样更好。任何使用scanf系列函数的人都应该受到惩罚,因为有些罪行永远不会太严重;-) - user180247
这应该是“在C++中使用scanf系列函数的任何人 - ...” - user180247

0

如果你通过_atoi64进行转换,它就能正常工作。

unsigned long l = _atoi64(str);


-3

5
这不是一个好的建议。原帖中明确要求使用“unsigned int”类型并提到了“_ultoa”等相关函数。原帖作者已经知道了atoi()、atol()等函数,但这些函数都是有符号类型,并且能够识别负号、进行溢出处理等。正确的做法是使用strtoul等函数。 - Armentage

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接