我试图找出是否有一种在C中转换字符串为整数的替代方法。
在我的代码中,我经常使用以下模式。
char s[] = "45";
int num = atoi(s);
那么,有没有更好的办法呢?
我试图找出是否有一种在C中转换字符串为整数的替代方法。
在我的代码中,我经常使用以下模式。
char s[] = "45";
int num = atoi(s);
那么,有没有更好的办法呢?
当前回答
好吧,我也有同样的问题。我想出了这个解决方案。这对我来说是最有效的。我试过用atoi(),但效果不太好。下面是我的解决方案:
void splitInput(int arr[], int sizeArr, char num[])
{
for(int i = 0; i < sizeArr; i++)
// We are subtracting 48 because the numbers in ASCII starts at 48.
arr[i] = (int)num[i] - 48;
}
其他回答
好吧,我也有同样的问题。我想出了这个解决方案。这对我来说是最有效的。我试过用atoi(),但效果不太好。下面是我的解决方案:
void splitInput(int arr[], int sizeArr, char num[])
{
for(int i = 0; i < sizeArr; i++)
// We are subtracting 48 because the numbers in ASCII starts at 48.
arr[i] = (int)num[i] - 48;
}
在c++中,你可以使用这样一个函数:
template <typename T>
T to(const std::string & s)
{
std::istringstream stm(s);
T result;
stm >> result;
if(stm.tellg() != s.size())
throw error;
return result;
}
这可以帮助您将任何字符串转换为任何类型,如float, int, double…
这个函数会帮助你
int strtoint_n(char* str, int n)
{
int sign = 1;
int place = 1;
int ret = 0;
int i;
for (i = n-1; i >= 0; i--, place *= 10)
{
int c = str[i];
switch (c)
{
case '-':
if (i == 0) sign = -1;
else return -1;
break;
default:
if (c >= '0' && c <= '9') ret += (c - '0') * place;
else return -1;
}
}
return sign * ret;
}
int strtoint(char* str)
{
char* temp = str;
int n = 0;
while (*temp != '\0')
{
n++;
temp++;
}
return strtoint_n(str, n);
}
裁判:http://amscata.blogspot.com/2013/09/strnumstr - - 2.版本的html
你可以自己卷!
#include <stdio.h>
#include <string.h>
#include <math.h>
int my_atoi(const char* snum)
{
int idx, strIdx = 0, accum = 0, numIsNeg = 0;
const unsigned int NUMLEN = (int)strlen(snum);
/* Check if negative number and flag it. */
if(snum[0] == 0x2d)
numIsNeg = 1;
for(idx = NUMLEN - 1; idx >= 0; idx--)
{
/* Only process numbers from 0 through 9. */
if(snum[strIdx] >= 0x30 && snum[strIdx] <= 0x39)
accum += (snum[strIdx] - 0x30) * pow(10, idx);
strIdx++;
}
/* Check flag to see if originally passed -ve number and convert result if so. */
if(!numIsNeg)
return accum;
else
return accum * -1;
}
int main()
{
/* Tests... */
printf("Returned number is: %d\n", my_atoi("34574"));
printf("Returned number is: %d\n", my_atoi("-23"));
return 0;
}
这样就可以做你想做的事情,而且不会杂乱。
不要使用来自ato…组。这些都坏了,几乎毫无用处。一个稍好的解决方案是使用sscanf,尽管它也不是完美的。
将字符串转换为整数,函数from strto…应该使用Group。在你的具体情况下,它将是strotol函数。