C++ 如何将 ascii 转换为无符号整数
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1496536/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
how to convert ascii to unsigned int
提问by dimba
Is there a method that converts string to unsigned int? _ultoa exists but couldn't find the vise verse version...
是否有将字符串转换为无符号整数的方法?_ultoa 存在但找不到虎钳诗版本...
回答by Michael Krelin - hacker
std::strtoul()
is the one. And then again there are the old ones like atoi()
.
std::strtoul()
是这个。然后还有像atoi()
.
回答by Martin
Boost provides lexical_cast.
Boost 提供了 lexical_cast。
#include <boost/lexical_cast.hpp>
[...]
unsigned int x = boost::lexical_cast<unsigned int>(strVal);
Alternatively, you can use a stringstream (which is basically what lexical_cast does under the covers):
或者,您可以使用字符串流(这基本上是 lexical_cast 在幕后所做的):
#include <sstream>
[...]
std::stringstream s(strVal);
unsigned int x;
s >> x;
回答by abelenky
sscanfwill do what you want.
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
回答by user3782474
It works if you go via _atoi64
如果你通过 _atoi64 就可以了
unsigned long l = _atoi64(str);
无符号长 l = _atoi64(str);
回答by Igor Oks
How about int atoi( const char * str )?
如何INT的atoi(为const char * STR) ?
string s("123");
unsigned u = (unsigned)atoi(s.c_str());