0

I'm trying to convert string like "1234" into a single integer like, n = 1234;

I'm using for loop for this but its saving the ASCII values instead of the actual values

below is the code

#include<stdio.h>

main()
{
    char lc[] = "12345";
    int i,n;
    p = lc;

    for(i=0;i<5;i++)
    {
        n = lc[i];
        printf("%d\n",n); 
    }
}

what am I missing ??

4 Answers4

1

If by "conversion" you mean printing then you should substract the ascii value of zero from the character , then the ascii of zero wil print as zero , the ascii of one as one ans so on,

char lc[] = "12345";
int i,n;

for(i=0;i<5;i++)
{
    n = lc[i]-'0';
    printf("%d\n",n); 
}
Dr.Haimovitz
  • 1,568
  • 12
  • 16
  • The key factor is that digit's ascii vals are corrusponding to the digits order so if the diff of two digit is x then the diff of the ascii values of those digits will be also x, '0' is the value that represent 0 , if you substract it from '0' you acctualy get zero value ('0'-'0') if you substract 'x' by '0' you will get 'x'-'0' which is like x-0 -> exectly x – Dr.Haimovitz Aug 01 '18 at 14:10
1

In your case you only assign in each iteration the current ASCII values to n, as you mentioned you want to convert the Stringinto an int.

A simple and powerful function to achieve that is alternative to your way: atoi(string)

In your case:

 char lc[] = "12345";
 int n = atoi(lc);
Alan
  • 589
  • 5
  • 29
  • Note, that this will not work correctly with non-numerical strings, as `atoi` will return `0` and won't be able to distinguish between the string `"0"` and "`sfsdsdf"`. – Eugene Sh. Aug 01 '18 at 14:24
0

Because we use ascii 48 represent digit 0, so a simply way to reach that is covert it by mod it, because the ascii define with increment, so 49 should be 1, and so on.

#include<stdio.h>

main()
{

    char lc[] = "12345";
    int i,n;
    //p = &lc;
    int ascii_base=48;
    for(i=0;i<5;i++)
    {
        n = lc[i];
        printf("%d\n",n - ascii_base);
    }
    return 0;
}

And if you want to save it back, and you can do it like:

#include<stdio.h>

main()
{

    char lc[] = "12345";
    int ln = sizeof lc;
    int i,n;
    //p = &lc;
    int ascii_base=48;
    for(i=0;i<5;i++)
    {
        n = lc[i];
        ln[i]=n - ascii_base;

    }
    printf("%s\n", ln);
    return 0;
}
Frank AK
  • 1,705
  • 15
  • 28
0

An alternative to atoi is to use sscanf which is useful if you want to convert multiple numbers that are in one string, especially if they are of different types such as a float and an integer. You will need to include stdio

char one_int[] = "12345";
char one_float = "3.14";
char a_float_and_an_int = "1024  6.28";

int first_int;
float first_float;
int second_int;
float second_float;

sscanf(one_int,"%d", &first_int);
sscanf(one_float, "%f", &first_float);
sscanf(a_float_and_an_int, "%d %f", &second_int, &second_float");
Spoonless
  • 561
  • 5
  • 14