2009-09-30 51 views

回答

15

std::strtoul()是一個。然後再次有像atoi()這樣的舊的。

+2

atoi不會做無符號,但?在Windows CRT中,如果發生溢出,它將返回一個錯誤(ERANGE)。 – Cheeso 2010-03-25 02:43:09

+0

Cheeso,對於我可以告訴的「我」來說,它是int ;-) – 2010-03-30 14:30:08

11

Boost提供lexical_cast。

#include <boost/lexical_cast.hpp> 
[...] 
unsigned int x = boost::lexical_cast<unsigned int>(strVal); 

或者,你可以使用一個字符串流(這基本上是lexical_cast的做什麼在幕後):

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

如果您想要非小數解釋,請參閱:http://stackoverflow.com/questions/1070497/c-convert- hex-string-to-signed-integer – Martin 2009-09-30 07:23:00

+0

我是唯一喜歡流式插入但喜歡流式抽取的人嗎?我會每次都使用函數(比如這個提升函數,儘管說實話我可能還會用atoi而不用考慮)。 – Steve314 2009-09-30 07:25:11

+0

是的,流提取是非常醜陋的,特別是因爲你不能用它初始化常量。但它也有點強大,因爲你可以使用操縱器來改變你的基礎,等等。 – Martin 2009-09-30 07:27:20

-3

如何int atoi (const char * str)

string s("123"); 
unsigned u = (unsigned)atoi(s.c_str()); 
+5

這根本不是一個好的建議。他被特別要求提供「unsigned int」,並提及諸如「_ultoa」之類的東西。海報知道atoi(),atol()等等。這些函數都是經過簽名和識別的 - 符號,可能會處理溢出等。正確的答案是使用像strtoul這樣的函數。 – Armentage 2011-04-19 04:31:34

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 
+0

我討厭scanf家族甚至回到了C,它從來沒有做過我想做的事情,而且大部分時間都是它造成的。如果你知道字符串符合你的要求是可以的 - 如果你已經檢查過它或者用其他代碼解壓縮了它,那麼爲什麼不使用atoi或者其他什麼? 任何人都使用scanf家庭功能 - 好吧,有一些罪行沒有懲罰可以過於苛刻;-) – Steve314 2009-09-30 07:30:55

+0

這應該是「任何人在C++中使用scanf家庭功能 - ...」 – Steve314 2009-09-30 07:32:17

0

如果通過_atoi64

無符號長L = _atoi64(STR)去它的工作原理;

相關問題