In C++, a character representing a decimal digit can be converted to its corresponding integer value using the character's position relative to '0'.
- For example, '9' can be converted to the integer 9 by subtracting '0'.
- For multi-digit values such as "123", use string-to-integer conversion methods such as stoi().
Examples:
Input: ch = '9'
Output: 9Input: ch = '5'
Output: 5
Approaches to Convert char to int
The following approaches can be used:
1. Using ASCII Character Conversion
The characters '0' to '9' have consecutive character codes. Therefore, subtracting '0' from a digit character gives its corresponding integer value.
For example:
'9' - '0' = 9
#include <iostream>
using namespace std;
int main()
{
char ch = '9';
// Convert digit character to integer
int num = ch - '0';
cout << num;
return 0;
}
Output
9
Explanation
- The character '9' is subtracted from '0'.
- Since digit characters are stored consecutively, the result is the integer 9.
2. Using stoi()
The stoi() function can also be used by first converting the character into a one-character string.
#include <iostream>
#include <string>
using namespace std;
int main()
{
char ch = '9';
// Convert char to a one-character string
string str(1, ch);
// Convert string to integer
int num = stoi(str);
cout << num;
return 0;
}
Output
9
Explanation
- The character '9' is first converted into the string "9".
- stoi() then converts the string into the integer 9.
Important Points
- The ch - '0' approach is valid only for digit characters ('0' to '9'); it should not be used for arbitrary characters such as 'A'.
- atoi() expects a null-terminated C-style string, so it should not be used directly with a single char; for multi-digit strings such as "1234", use stoi().