编程实现字符串数转化成整数的办法

来源:百度知道 编辑:UC知道 时间:2024/06/06 10:52:50
不能用atoi()函数
要求用C++/C实现

#include <stdlib.h>
#include <stdio.h>
#include <string.h>
int Atoi(const char * pstr)
{
int i = strlen(pstr);
int j = 0;
int sum = 0;
int flag = 0;
if (pstr[0] == '-') // 处理符号
{
flag = 1;
j ++;
}
else if (pstr[0] == '+')
j ++;
for(; j < i; j++)
{
sum = sum * 10 + (pstr[j]-48);
}
return (flag == 1 ? -sum : sum);
}
int main()
{
char p[10];
gets(p);
printf("%d\n", Atoi(p));
return 0;
}

直接使用指针

#include <stdio.h>
int Atoi(const char * pstr)
{
int j = 0;
int sum = 0;
int flag = 0;
if (*pstr == '-') // 处理符号
{
flag = 1;
pstr ++;
}
else if (*pstr == '+')
pstr ++;
while (*pstr != NULL)
{
sum = sum * 10 +