Here is a programming task:
Write a program with a function that converts a string of digits into an integer value. Do not use the
strtol()
function or any other standard C library function. Write your own!
I wanted this program to work perfectly with no errors. First I did the power function (power) and then next is function that return the length of a string (lent) and lastly is function that gives the value of asciicode (ascton).
In the main function there is a loop for the string where it multiple the value of how much zeros in has after it. For example, the string is "1100" so the first 1 is 1000 then this value is stored in variable z, and then this works for the other character and add it to variable z. At the end it return z as an integer of the string.
Is this code efficient, or did I use the "long way"? Please give me some hints how I can write better, cleaner and more readable code. Any feedback is appreciated.
#include <stdio.h>
#include <math.h>
int powe(int ex , int po)
{
int z = 1;
for (int i = 0; i < po; i++)
{
z = z * (10 * 1);
}
return z;
}
int lent (char a [20])
{
int i=0;
int l = 0;
for(i=0 ; a[i] != '\0';i++)
{
l++;
}
return l;
}
int ascton (int a)
{
int asciicode[10] = {48,49,50,51,52,53,54,55,56,57};
for(int i = 0; i < 10; i++)
{
if (a == asciicode[i])
{a = i;
break;}
else continue;
}
return a;
}
int main(void) {
int z = 0;
char sn[20];
printf("enter your string number!:");
scanf("%s",sn);
int s = lent(sn);
for(int i = 0; sn[i] != '\0';i++)
{
int k = 0;
k = ascton(sn[i]);
z = z + (k * powe(10, s-1));
s = s-1;
}
printf("%d",z);
}
```
int f(char x[20]);
because that function can't accept an arbitrary c-str; it will only accept a fixed-width array. You could prototype a variable-width array,int f(char x[]);
, or simply useint f(char *x);
, which I feel is preferable because it's standard. There's another way to define yourasciicode[]
array too:const char *asciicode = "0123456789";
. However, my favorite way to go from a single ascii digit to an integer 0-9 is simplyint i = a - '0';
\$\endgroup\$int f(char x[static 20])
(which would promise that all 20 array elements were definitely readable, even if the C string actually ended after 2 bytes, right before an unmapped page). (reference) As written, the20
is ignored by C, and is confusing / misleading only for humans. But yes, a sane prototype would beunsigned f(const char *s)
. \$\endgroup\$