如何将字符串转为数值
1个回答
展开全部
通过下标取字符串的每一位,然后按ASCII码上的值变为数字,以字符串为全整数为例,处理函数如下:
#include <stdio.h>
#include <string.h>
int toInt(char *s);
int main(int argc,char **argv)
{
int num;
char *s = "1234";
num = toInt(s);
printf("num = %d\n",num);
return 0;
}
int toInt(char *s)
{
int temp = 0;
int res = 0;
int len = strlen(s);
int i = 0;
for(i = 0;i < len;i++)
{
temp = s[i] - '0';
res = res *10 + temp;
}
return res;
}
#include <stdio.h>
#include <string.h>
int toInt(char *s);
int main(int argc,char **argv)
{
int num;
char *s = "1234";
num = toInt(s);
printf("num = %d\n",num);
return 0;
}
int toInt(char *s)
{
int temp = 0;
int res = 0;
int len = strlen(s);
int i = 0;
for(i = 0;i < len;i++)
{
temp = s[i] - '0';
res = res *10 + temp;
}
return res;
}
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询