Reputation: 3
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;
}
Upvotes: 0
Views: 110
Reputation: 1937
There are few issues in your code. For reducing risks of UB:
char[]
as string, its size should allow for accommodating the \0
terminating character.int b
).scanf()
cautiously if you read a string. Overflow leads to UB. Use a field width specifier.pow()
is double
).pow()
altogether.Please, see the comments along the lines based on your code:
#include <stdio.h>
#include <string.h>
int main(void)
{
char a[7]; // extra byte for '\0'
int i, l, b = 0;//initialize local variable b
int ten = 1;
scanf("%6s",a); //should use a field width specifier
l = strlen(a) - 1;
for( i=l ; i>=0 ; i--, ten*=10 )
b += (a[i]-48)*ten; //do as simple math as practical
printf("%d\n",b);
return 0;
}
Upvotes: 0
Reputation: 409136
The problem is most likely undefined behavior because you use uninitialized variables.
In the expression b=b+...
you use the variable b
without initializing it first. Non-static local variables are not initialized and will have an indeterminate value. Using them without initialization leads to UB. Initialize it to zero:
int i, b = 0;
You also have problems with the user entering to many characters for the array a
and going out of bounds. You also don't have any checks that the user actually only entered digits.
Upvotes: 3