shivam
shivam

Reputation: 3

convert the numeric string to integer value

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

Answers (2)

user3078414
user3078414

Reputation: 1937

There are few issues in your code. For reducing risks of UB:

  1. If you treat char[] as string, its size should allow for accommodating the \0 terminating character.
  2. If your code doesn't initialize non-static local variable values, you should do it explicitly (variable int b).
  3. Treat scanf() cautiously if you read a string. Overflow leads to UB. Use a field width specifier.
  4. Don't mix data types (return of pow() is double).
  5. Make your code as lean as possible, with as little math as practical, especially inside loops. You don't need 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

Some programmer dude
Some programmer dude

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

Related Questions