Methods of Converting Char to Int in the C Programming Language
There are three different methods of converting a character to an integer in the C programming language, and we are going to discuss all of them below:
Method 1: The “Typecasting” Method
In this method, we will simply typecast our character to the integer data type. For that, you can take a look at the following C script:
In this script, after including the desired libraries, we have initialized a character type variable “c” with the character “a” (that we intend to convert into an integer). Then, we declare an integer type variable “x”. We have equalized this variable to the typecasted value of the character “c”. After that, we used a “printf” statement to print the integer value on the terminal.
Then, to compile this program, we ran the command shown below:
The execution of this script was done with the help of the following command:
The converted value of our character to an integer is shown in the image below:
Method 2: The “sscanf” Method
In this method, we will be using the “sscanf” function for converting a character to an integer in C. For that, we have used the following C script:
In this program, we have defined a constant character type variable “*c” and have assigned to it the value “123”. After that, we defined an integer “x”. Then, we used the “sscanf” function to convert the value of “c” to an integer and save it to “x”. Finally, we have printed the value of “x” with the help of the “printf” statement.
The converted value of our constant character to an integer is shown in the image below:
Method 3: The “atoi” Method
In this method, we will be using the “atoi” function for converting a given character to an integer in the C programming language. To do so, we have written the C script that follows:
Again, in this script, we have used the very same constant character type variable that we have used in our second method. After that, we defined an integer variable “x” and equalized it to the converted value of the constant character “c” while making use of the “atoi” function. Finally, we have printed this converted value on the terminal.
The converted value of our constant character to an integer is shown in the image below:
Conclusion
This guide primarily talked about the conversion of the character data type in the C programming language to an integer. In this regard, we shared three different methods with you. Now, it is totally up to you which method you prefer to use for converting your desired character to an integer while using the C programming language.