I'm a freshman in computer science and a new member to this forum. I'd like to convert the string representation of a number e.g "456" into its integer equivalent i.e. 456.
As for character representation of single digits e.g. "6", I'm able to convert it to its integer equivalent by doing:
char myChar = "6";
int asciiVal = myChar - '0'; //produces the integer 6 now.
Could anyone show me how the string representation of a number like "456" can be converted to its integer equivalent?
#include <stdio.h>
int main(void)
{
int i, value;
const char text[] = "456";
for (i = 0, value = 0; text [ i ] != '\0'; ++i)
{
value *= 10;printf("value *= 10 = %3d, ", value);value += text [ i ] - '0'; /* add value of current digit character */
printf("value += '%c' - '0' = %3d\n", text [ i ], value);
}
return 0;
}
/* my output
value *= 10 = 0, value += '4' - '0' = 4
value *= 10 = 40, value += '5' - '0' = 45
value *= 10 = 450, value += '6' - '0' = 456
*/
#include <stdio.h>
int main(void)
{
int i, value;
const char text[] = "456";
for ( i = 0, value = 0; text [ i ] != '\0'; ++i )
{
int digit = text [ i ] - '0'; /* get value of current digit character */
printf("value = %3d, %3d * 10 = %3d, ", value, value, value * 10);value = 10 * value + digit;printf("digit = %d, value = %d\n", digit, value);
}
return 0;
}
/* my output
value = 0, 0 * 10 = 0, digit = 4, value = 4
value = 4, 4 * 10 = 40, digit = 5, value = 45
value = 45, 45 * 10 = 450, digit = 6, value = 456
*/
Thanks very much for the help. In fact I forgot to mention earlier when posting this problem that I'm not suppose to use built-in functions like atoi or atol for such conversions. Nevertheless, thanks to everyone for their help.
Dave,
Your solution provided the answer to my problem. thanks.
No one has posted to this discussion for at least three months. Please let old threads die and do not reply to them unless you feel you have something new and valuable to contribute that absolutely must be added to make the discussion complete. Otherwise, please start a new thread in this forum instead.
This thread is currently closed and is not accepting any new replies.