Helper Function: Check if character is a digit or not
April 26, 2016
Helper Function: Return the terminating number in a string
April 26, 2016

Helper Function: 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.

Leave a Reply

Your email address will not be published. Required fields are marked *