I'm making a function that inputs a string class number and translates it into integers.
for example. I punch in 123 I'll get back 123 as an integer, or I punch in 1D2F I...guess I get it back? But I figured I'll turn any base number back to decimal. (But how would I make this string into a decimal if I'm not completely sure you can do math effectively with strings?
So far for my stringToInt function I have.
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;
}
I figured I can use the ascii numbers to get characters to integers. But when I run it whatever I put it is returned as 0. And I really am not sure how to approach the base number problem (What to do with A-F, perhaps if statements? Is there a more elegant way of doing this?). Can I call my base function within my StringToInt function? Or is there already a function I can use to accomplish this? Am I just complicating matters?
my base function (Which seems to work I guess? There seems to be a slight issue with binary numbers when I punch in 100 and say its in base 2 I get 24 back as it's decimal equivalent. Otherwise it works perfectly.)
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;
}
The old C way (
atoi
):Using
std::istringstream
:C++11's
std::stoi
:which under the hood uses
std::strtol
:And to add an example for @polkadotcadaver's mention of
boost::lexical_cast
:Don't forget to add appropriate error handling!