Friday, July 31, 2009

How do you convert a character array to an int in C?

if i have a number stored as a String, how do i convert it into an integer type? In java this would be Integer.parseInt(blah) but what about in C?

How do you convert a character array to an int in C?
The library stdlib.h has the function that does what you want.





int atoi (const char *s)
Reply:As Otheres Said V Have Inbuild Functions In C To Solve The Problem





i dont think that being a programmer v need to use inbuild functions to


solve our problem.and a language like C which gives us the access to everythink in computer and v still use inbuild funtions to solve the problems NO WAY





i will tell u the easyest way to convert string to interger ("Only if they r numbers in characters")





let us write a function to solve ur problem





int C_I(char str[])


{





int num = 0 ;


for(int i=0;str[i] != '\0'; i++)


{


num = num*10 ;


switch(str[i])


{


case '0' :


num = num + 0 ;


case '1' :


num = num + 1 ;


case '2' :


num = num + 2 ;


case '3' :


num = num + 3 ;


case '4' :


num = num + 4 ;


case '5' :


num = num + 5 ;


case '6' :


num = num + 6 ;


case '7' :


num = num + 7 ;


case '8' :


num = num + 8 ;


case '9' :


num = num + 9 ;


}


}


return num ;


}





atlast i want to tell one thing using our own functions is not always possible but when v can do it why should v use inbuild functions





now let me xplain wht i have done





firstly i have created my function with name C_I and return type is int





using a for loop i am going form str[0] to str[n] untill str[n] != '\0'





here '\0' is equal to NULL. i have used varialble num which intially multiplyes itself with then and then acc to the character it addeds that num to itself............





Its as easy as that





bye take care
Reply:int Number = atoi( string );

carnation

No comments:

Post a Comment