I was trying to convert the string of numbers into integer value with the following code. The output is always one less than the original value. I am not getting what's wrong with my code.
#include<stdio.h>
#include<conio.h>
#include<stdlib.h>
#include<math.h>
#include<string.h>
int main(){
char a[6];
int i,b;
scanf("%s",a);
for(i=strlen(a)-1;i>=0;i--){
a[i]=a[i]-48;
b=b+a[i]*pow(10,(strlen(a)-i-1));
}
printf("%d",b);
getch();
return 0;
}
strtol. Also don't use magic numbers. If by48you mean the character'0'then say so explicitly.powhere, just a simple multiplication with10.bvalue, shall we also assume negative values aren't an option, nor any value larger than 99999?bto 0. Start at the left of the string. For each digit that you see, multiplybby 10 and add in the digit. When you stop seeing digits, you're done. That way you don't even have to callstrlen.strlenon the modified string. If there is '0' in your string, thenstrlenwill return a different value than originally.