topic description
- myatoi implementation; elementtype myatoi( const char*str );
- Translates the integer value in the byte string pointed to by str into a meaningful integer output.
- Example: hao123:123 -hao123:123 hao-123:-123 hoo123de-45:12345 +123haode:123 haode-45ni321:-45321
- In output, the plus or minus sign is optional.
- In output, digits are required.
Code
#include <stdio.h>
#include <stdlib.h>
#define MAXSIZE 100
typedef long long elementype;
elementype myatoi(const char* str);
elementype strtonum(int numbers[], int size);
int main()
{
char str[MAXSIZE];
elementype numstr;
scanf_s("%s", str, MAXSIZE);
numstr = myatoi(str);
printf("%lld\n", numstr);
system("pause");
return 0;
}
elementype myatoi(const char* str)
{
elementype ret = 0;
int firstnum = 1;
int flag = 1;
int numbers[MAXSIZE] = {
0 };
int size = 0;
while (*str != '\0')
{
if (*str >= '0' && *str <= '9')
{
if (firstnum)
{
if (*(str - 1) == '-')
{
flag = -flag;
}
firstnum = 0;
}
numbers[size++] = *str - '0';
}
++str;
}
ret = strtonum(numbers, size);
return (flag * ret);
}
elementype strtonum(int numbers[], int size)
{
elementype ret = 0;
elementype weight = 1;
for (int i = size - 1; i >= 0; --i)
{
ret += numbers[i] * weight;
weight *= 10;
}
return ret;
}
Debug results