Thursday, July 30, 2009

Conter char to int?

Please suggest how to convert a char variable to integer.


I mean say there is one char variable named "str", which have some value assigned to it as a zero-th element. How to assign this value to an integer variable?


I repeat the language is C.

Conter char to int?
If you want to convert a char array into an int, you could use the atoi() function.





{


int x;


char number[] = "12345";





x = atoi(number);


}





Then x is an integer equal to 12345.
Reply:int a = str[0];


you don't need to convert anything explicitly.


or, if you meant to use a numerical value of the character, not the byte code - i.e., convert '1' to 1 etc., then do this:


int a = str[0] - '0';





(all numerical symbols are coded sequentually, starting with 0, so the code for 1 is 1 more than that for 0 etc.)


No comments:

Post a Comment