...

/

Solution Review: Convert String Into an Integer

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!

Press + to interact
# include <stdio.h>
int stringToInt (char *str);
int main( )
{
char str[ ] = {'1', '2', '3', '\0'};
printf ("The String is: %s\n", str);
printf ( "The number is: %d\n", stringToInt(str) ) ;
return 0 ;
}
int stringToInt (char *str){
// Initialize variables
int num = 0, i ;
// Traverse string
for ( i = 0 ; str [ i ] != '\0' ; i++ )
{
// If string contains digit convert it into integer
if ( str[ i ] >= 48 && str[ i ] <= 57 )
num = num * 10 + ( str[ i ] - 48 ) ;
else
{
// If string does not contain digit return -1
printf ( "Not a valid string\n" ) ;
return -1 ;
}
}
return num;
}

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 ...