将字符串转换为整数

Turning a string into an integer?

本文关键字:整数 转换 字符串      更新时间:2023-10-16

我正在制作一个函数,该函数输入字符串类编号并将其转换为整数。

例如。我输入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。我真的不知道如何处理基数问题(A-F怎么办,也许是if语句?有更优雅的方法吗?)。我可以在StringToInt函数中调用我的基函数吗?或者已经有一个功能可以用来实现这一点了吗?我只是把事情弄复杂了吗?

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;
   }

旧的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);

不要忘记添加适当的错误处理