Solution Review: Convert String Into an Integer
Follow the step-by-step instructions to convert a string into an integer.
We'll cover the following...
Solution
Press the RUN button and see the output!
Explanation
We will traverse the characters in the given string, str, and convert any digits into integers. Otherwise, we will simply return -1 to the calling point.
Line 15: Initializes the variable, num, that will store the integer number.
Line 17: The for loop traverses the characters in the string, str, from the index, 0, until we encounter a terminating character, '\0'.
Line 20: From the ASCII Table, you can see that characters whose ASCII code is between 48 to 57 are digits. This line verifies whether or not the current character is a digit by checking whether the current character’s ASCII code lies between 48 to 57.
Line 21: If the current character is a digit, then convert the current character into an integer and store it in num. To convert the given character into an integer, we will subtract 48 from it. Since a string can contain more than one character, we will multiply the nums by 10 to store the digit at the next place. For example, the first digit will be stored at the unit’s place; then, we will multiply the num by 10 so that the next digit will be stored at ten’s place.
Line 26: For a non-digit character, simply return -1 to the calling point.