将字符串转换为整数
Turning a string into an integer?
我正在制作一个函数,该函数输入字符串类编号并将其转换为整数。
例如。我输入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);
不要忘记添加适当的错误处理
相关文章:
- 努力将整数转换为链表。不知道我在这里做错了什么
- 如何在C++中将整数转换为其数字数组
- 如果整数与指针大小相同,则重新解释将整数转换为指针双射是否具有双射作用?
- 将最小值整数转换为无符号长整型
- 为什么我们不能将使用异或运算找到的整数转换为字符?
- 在C++中,将无符号整数转换为八进制表示,反之亦然的最佳方法是什么
- 将74位整数转换为以31为底的整数
- 独立于实现的浮点/整数转换
- 以最少的步骤将给定整数转换为另一个整数
- 浮点到整数转换出错(即使浮点数已经是整数)
- 了解双精度转换与整数转换中的整数与截断关系
- 禁止具有精度损失的整数转换
- 将任意整数转换为 void*
- 将 32 位大端有符号整数转换为有符号小端整数
- char a[0] 使用 itoa() 将整数转换为字符串的目的
- 使用函数时从整数转换为字符串
- 尝试从整数转换为字符串的月份
- 如何在C++中将整数转换为字节,以便 Unity 在通过 UDP 传输后能够理解它们
- 如何将 Q 格式的整数转换为浮点数(反之亦然)
- 如何避免字符串到整数转换情况下的无效参数异常