Files
lab1_git/atoi_2.0.c
2025-11-01 06:07:58 -04:00

58 lines
1.0 KiB
C

#include <stdio.h>
#include <string.h>
int myatoi(char *s, int l, int base);
int main(int argc, char **argv)
{
printf("Print your string number\n");
char s[100]; scanf("%s", s);
printf("Enter your string number base\n");
int base;
scanf("%d", &base);
printf("Your converted number is %d\n", myatoi(s, strlen(s), base));
return 0;
}
int myatoi(char *s, int l, int base)
{
int result = 0;
int is_pos = 1;
int symb;
int d;
for(int i=0; i < l; i++)
{
symb = (int)s[i];
if((int)s[i]=='-')
{
is_pos = -1;
}
else if(base <= 10)
{
if((int)s[i] < '0' || (int)s[i] > '9')
{
printf("Not a number\n");
result = 0;
break;
}
result = result * base + ((int)s[i] - '0');
}
else
{
if (symb >= '0' && symb <= '9')
{
d = symb - '0';
}
else if (symb >= 'A' && symb <= 'Z')
{
d = symb - 'A' + 10;
}
else if (symb >= 'a' && symb <= 'z')
{
d = symb - 'a' + 10;
}
result = result * base + d;
}
}
result = result * is_pos;
return result;
}