2013-12-08 49 views
-1

我正在做一個函數,輸入一個字符串類的數字,並將其轉換爲整數。例如將字符串轉換爲整數?

。我衝123,我會回到123作爲一個整數,或者我衝1D2F我......我猜得到它回來?但我想我會把任何基數恢復到十進制。 (但我怎麼才能讓這個字符串轉換爲十進制如果我不能完全肯定,你可以用串有效做數學題?

到目前爲止我stringToInt功能我有。

int StringToInt (string inputString){ 
    int i; 
    int newIntegerLine; 

     for (i=0; i<inputString.length();i++){ 
     //subtracts the ascii number of 0 from 
     //whatever character you input 
     newIntegerLine= (inputString.at(i)- '0'); 
     } 

    return newIntegerLine; 
} 

我想我可以使用ascii數字來將字符轉換爲整數,但是當我運行它時,它會返回爲0.我真的不知道如何處理基本數字問題(如何處理AF,或者如果語句? )我可以在我的StringToInt函數中調用我的基函數嗎?或者已經有一個函數可以用來實現這個功能嗎?我只是把事情複雜化了嗎?

我的基本功能(這似乎工作我猜?二進制數似乎有一個小問題,當我衝入100並且說它在基數2時,我得到24回,因爲它是十進制等值。否則,它完美的作品)

int baseToDecimal (int numInput, int base){ 
    int i, modSum; 
    modSum=numInput%10; 
    for(i=base;(numInput/=10)!=0;i*=base) 
     modSum+=numInput*i; 
    return modSum; 
    } 
+0

std :: stoi(string)有什麼問題? – ScarletAmaranth

+0

無知我想。我簡直不知道一個叫做stoi的函數。我會查找它。 – Slender

+0

@ScarletAmaranth我認爲它叫'atoi' http://www.cplusplus.com/reference/cstdlib/atoi/ – elyashiv

回答

3

舊的C方式(atoi):

std::string foo = "1337"; 
int bar = atoi(foo.c_str()); 

使用std::istringstream

std::string foo = "1337"; 
int bar; 
std::istringstream(foo) >> bar; 

C++ 11的std::stoi

std::string foo = "1337"; 
int bar = std::stoi(foo); 

其引擎蓋下使用std::strtol

std::string foo = "1337"; 
int bar = std::strtol(foo.str(), nullptr, 10); 

並且加入了對@polkadotcadaver的提boost::lexical_cast一個例子:

std::string foo = "1337"; 
int bar = boost::lexical_cast<int>(foo); 

不要忘記添加相應的錯誤處理

+0

非常非常小的一點 - 與lexical_cast沒有必要使用.c_str()。 – polkadotcadaver

+0

你是對的,謝謝!從std :: strtol例子複製粘貼:D –