Convert String to Number

Given a String. Write a function that convert it to number. Such functions are used in larger programs as helper functions.

Input: char* str = "0324";
Output: int 324;

Solution:

int strToNum(char* str)
{
    int num = 0;
    for(int i=0; str[i]!='\0';i++)
    {
        int digit = str[i] - '0';
        num = num*10 + digit;
    }
    return num;
}
The function removes one digit from the string at a time and keep adding it to the number.

0 Comments

Leave a comment