2013-12-08 233 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 –