C program to convert string to integer without using atoi function: It is frequently required to convert a string to an integer in applications. String should consists of digits only and an optional ‘-‘ (minus) sign at beginning for integers. For string containing other characters we can stop conversion as soon as a non digit character is encountered but in our program we will handle ideal case when only valid characters are present in string. Library function atoi can be used to convert string to an integer but we will create our own function.

[ad type=”banner”]

C programming code

[pastacode lang=”c” manual=”%2F%2F%20C%20program%20to%20convert%20string%20to%20integer%20without%20using%20atoi%20function%0A%23include%20%3Cstdio.h%3E%0A%20%0Aint%20toString(char%20%5B%5D)%3B%0A%20%0Aint%20main()%0A%7B%0A%20%20char%20a%5B100%5D%3B%0A%20%20int%20n%3B%0A%20%0A%20%20printf(%22Input%20a%20valid%20string%20to%20convert%20to%20integer%5Cn%22)%3B%0A%20%20scanf(%22%25s%22%2C%20a)%3B%0A%20%0A%20%20n%20%3D%20toString(a)%3B%0A%20%0A%20%20printf(%22String%20%20%3D%20%25s%5CnInteger%20%3D%20%25d%5Cn%22%2C%20a%2C%20n)%3B%0A%20%0A%20%20return%200%3B%0A%7D%0A%20%0Aint%20toString(char%20a%5B%5D)%20%7B%0A%20%20int%20c%2C%20sign%2C%20offset%2C%20n%3B%0A%20%0A%20%20if%20(a%5B0%5D%20%3D%3D%20′-‘)%20%7B%20%20%2F%2F%20Handle%20negative%20integers%0A%20%20%20%20sign%20%3D%20-1%3B%0A%20%20%7D%0A%20%0A%20%20if%20(sign%20%3D%3D%20-1)%20%7B%20%20%2F%2F%20Set%20starting%20position%20to%20convert%0A%20%20%20%20offset%20%3D%201%3B%0A%20%20%7D%0A%20%20else%20%7B%0A%20%20%20%20offset%20%3D%200%3B%0A%20%20%7D%0A%20%0A%20%20n%20%3D%200%3B%0A%20%0A%20%20for%20(c%20%3D%20offset%3B%20a%5Bc%5D%20!%3D%20’%5C0’%3B%20c%2B%2B)%20%7B%0A%20%20%20%20n%20%3D%20n%20*%2010%20%2B%20a%5Bc%5D%20-%20’0’%3B%0A%20%20%7D%0A%20%0A%20%20if%20(sign%20%3D%3D%20-1)%20%7B%0A%20%20%20%20n%20%3D%20-n%3B%0A%20%20%7D%0A%20%0A%20%20return%20n%3B%0A%7D” message=”” highlight=”” provider=”manual”/]

Similarly you can convert string to long.

[ad type=”banner”]

Output of program:

C program to convert string to integer without using atoi function

Categorized in: