The code I have written is as follows:
#include<stdio.h>
#include<math.h>
#include<string.h>
int strToint(char []);
int main()
{
char str[20];
printf("Enter the string-");
gets(str);
printf("\nthe integer is %d ",strToint(str));
return 0;
}
int strToint(char str[])
{
int i,a,sum=0,k,j;
a=strlen(str);
for(i=0;i<a;i++)
{
k=str[i]-'0';
j=pow(10,a-i-1);
sum+=k*j;
}
return sum;
}
If I enter the input as, say 567, I get 562 but I do not see why. I feel this is probably related to the pow function.
Help is appreciated. Thanks!
sscanf? And why would you callstrlen()and so iterate over the string twice? And why callpow()which is a floating point function. Use integer arithmetic if you must do this. And what if your string doesn't contain all digit characters?