how to convert a digit in string into its equivalent int number? for ecample to convert a[i]=3 to int b=3?
substract the ascii of 0 from your ascii like if a[i]=3 a[i]-'0' ascii of 3 is 51 and 0 is 49 51-49 =3 will give you integer eqivalent
ok thanks I will try it?
I am not getting it if it cross 9 then how to convert it into int? that is to convert a[i]=20 to int 20?
ok there is a inbuild funciton atoi that will do your purpose try this code #include<stdio.h> #include<stdlib.h> int main () { int i; char buffer [256]; printf ("Enter a number: "); fgets (buffer, 256, stdin); i = atoi (buffer); printf ("The value entered is %d.",i); return 0; }
or creating your own atoi but it wont handle the -ve numbers int myAtoi(char *str) { int res = 0; // Initialize result // Iterate through all characters of input string and update result for (int i = 0; str[i] != '\0'; ++i) res = res*10 + str[i] - '0'; // return result. return res; }
@03225186213 hope you get it
why you multiplied res by 10
@nubeer
As you go through a string, you can have more than one number. you multiply by 10 to make them land in the right spot. string i[] = "253" i[0] = 2 i[1] = 5 i[2] = 3 2+5+3 = 10 \(10\ne 253\) \((2*10+5)*10+3 \implies \) \((20+5)*10+3 \implies \) \(25*10+3 \implies \) \(250+3 \implies \) \(253 = \)"253" Get why the * 10 now?
Join our real-time social learning platform and learn together with your friends!