1.

Write a function, my_atoi, similar to the library function atoi that returns the numeric value corresponding to the string passed to it as an argument.

Answer»

#include<stdio.h>

main()

{

long int n=0;

char str[25];

clrscr();

printf ("\nEnter the string:-> ");

gets(str); my_atoi(str,&n);

printf ("\nInteger Equvalent of string %s=%ld",str,n);

getch();

}

my_atoi(char str[25],long int *num)

{

int i=1;

long int s=1,l=0,j;

float po10=1;

//Trimming the string for integers

for (i=0;str[i]!='\0';i++)

{

if (str[i]==' ')

{

for (j=i;str[j]!='\0';j++)

str[j]=str[j+1];

i--;

}

else if (str[i]>=48 && str[j]<=57)

continue;

else

{

str[i]='\0';

break;

}

}

l=strlen(str);

for (i=l-1;i>=0;i--)

{

switch (str[i])

{

case 48:s*=0;break;

case 49:s*=1;break;

case 50: s*=2;break;

case 51: s*=3;break;

 case 52: s*=4;break;

case 53: s*=5;break;

case 54: s*=6;break;

case 55: s*=7;break;

case 56: s*=8;break;

case 57: s*=9;break;

}

*num+=s;

po10*=10;

s=po10;

}

}



Discussion

No Comment Found

Related InterviewSolutions