In C++, char serves as a data type that signifies an individual character, like 'A' or '5'. At times, there may be a need to convert this character into an integer. This requirement often arises when dealing with numerical digits or when determining the ASCII value associated with a character. This conversion can be achieved through various techniques, including type casting, arithmetic operations, and utilizing functions from the standard library.
There are several methods that can help to convert a char to an int in C++. Some of them are as follows:
- Convert char to int Using Typecasting
- Using ASCII Value of a Character
- Convert a Digit Character to its Integer Value
- Using atoi for Character Arrays
- Using stoi for std::string
- Convert Character Array to Integer using strtol
Now, we will discuss these methods one by one.
1) Convert char to int Using Typecasting
In C++, typecasting serves as a method to explicitly instruct the compiler to interpret a variable of one data type as another data type. By typecasting a char to an int, we obtain the ASCII value corresponding to the character.
Syntax
Using C-Style
It has the following syntax:
int num = (int)charVar;
Or using C++ style
int num = static_cast<int>(charVar);
C++ Example to convert char to int using Typecasting
Let's consider a scenario to demonstrate the process of converting a character to an integer using Typecasting in the C++ programming language.
Example
#include <iostream>
using namespace std; //using standard namespace
int main() { //Main Function
char ch = 'B';
// C-style cast
int ascii1 = (int)ch;
// C++ style cast
int ascii2 = static_cast<int>(ch);
cout << "Using C-style cast: ASCII value of '" << ch << "' is " << ascii1 << endl;
cout << "Using static_cast: ASCII value of '" << ch << "' is " << ascii2 << endl;
return 0;
}
Output:
Using C-style cast: ASCII value of 'B' is 66
Using static_cast: ASCII value of 'B' is 66
Explanation
In this illustration, we showcase the process of converting a character to its ASCII integer representation by employing both C-style casting ((int)ch) and contemporary C++ casting (static_cast<int>(ch)). Both techniques yield the ASCII value corresponding to the character 'B', which is 66.
2) ASCII Value of a Character
In C++, each character is assigned an ASCII value, which corresponds to a numerical representation of the character within the computer system. Within C++, every character is essentially stored as a numeric value according to the ASCII (American Standard Code for Information Interchange) standard.
For example:
- 'A' -> 65
- 'B' -> 66
- '0' -> 48
- '9' -> 57
So, when we convert a character to an integer, we are essentially retrieving its ASCII value.
Syntax
It has the following syntax:
int ascii = ch;
C++ ASCII Value of a Character Example
Let's consider an instance to demonstrate the process of converting a character to an integer by utilizing the ASCII value of the character in C++.
Example
#include <iostream>
using namespace std; //using standard namespace
int main() { //Main Function
char ch = 'A';
int asciiValue = ch;
cout << "The ASCII value of " << ch << " is " << asciiValue << endl;
return 0;
}
Output:
The ASCII value of A is 65
Explanation
In this instance, we assigned the character ch to an integer variable named asciiValue. The C++ language automatically converts the character to its corresponding ASCII value.
3) Convert a Digit Character to its Integer Value
Characters such as '1', '2', '3', and so on, differ from integers 1, 2, 3 as they are stored as characters in memory. To utilize them as numerical values, it's essential to perform the correct conversion. For instance, when dealing with a character representing a number like '5' and we require the integer 5 itself rather than its ASCII representation, a simple approach is to subtract '0' from the character.
Syntax
It has the following syntax:
int num = digit - '0';
C++ Example to Convert a Digit Char to Int
Let's consider an example to demonstrate the process of converting a character representing a digit to an integer in C++.
Example
#include <iostream>
using namespace std; //using standard namespace
int main() { //Main Function
char digitChar = '7';
int number = digitChar - '0';
cout << "The integer value is " << number << endl;
return 0;
}
Output:
The integer value is 7
Explanation
In this instance, we transform a numeric character ('7') into its respective integer value by subtracting the character '0' from it. As characters are stored as ASCII values internally, this process reveals the true numerical representation.
Why does it work?
In ASCII, '0' is 48, '1' is 49, ..., '9' is 57.
So, '7' - '0' = 55 - 48 = 7.
4) Using atoi for Character Arrays
If our numerical value is stored as a string or an array of characters (e.g., "123"), we can utilize the atoi function.
Syntax
It has the following syntax:
int num = atoi("123");
C++ Example to convert char to int using atoi function
Let's consider a scenario to demonstrate the process of converting a character to an integer by utilizing the atoi function in C++.
Example
#include <iostream>
#include <cstdlib> // for atoi()
using namespace std; //using standard namespace
int main() { //Main Function
const char* numStr = "123";
int number = atoi(numStr);
cout << "Converted number is " << number << endl;
return 0;
}
Output:
Converted number is 123
Explanation
In this instance, we employ the atoi function from the <cstdlib> header to change a C-style string ("123") into an integer. Subsequently, the integer 123 is displayed on the console.
Note: The atoi function only works with character arrays (C-style strings), not with a single char.
5) Using stoi for std::string
If std::string is being utilized instead of a character array, employ the stoi function.
Syntax
It has the following syntax:
int num = stoi("456");
C++ Example to convert char to int using stoi function
Let's consider a scenario to demonstrate the conversion of a character to an integer using the stoi function in C++.
Example
#include <iostream>
#include <string>
using namespace std; //using standard namespace
int main() { //Main Function
string numStr = "456";
int number = stoi(numStr);
cout << "Converted number is " << number << endl;
return 0;
}
Output:
Converted number is 456
Explanation
In this instance, we employ the stoi function from the <string> header to transform a std::string ("456") into an integer. Subsequently, the converted integer value of 456 is displayed on the console.
6) Convert Character Array to Integer using strtol
The strtol stands for string to long. It is a function from the C standard library that converts a C-style string (character array) to a long int. It's more powerful than atoi because:
- It allows us to check for errors.
- We can choose the number system (like decimal, hexadecimal, octal).
- We can handle strings with extra characters.
Syntax
It has the following syntax:
long strtol(const char* str, char** endptr, int base);
- str: It represents to the input C-string.
- endptr: It represents a pointer to the first invalid character (can be nullptr if not needed).
- base: It represents the number system (10 for decimal, 16 for hexadecimal, etc.).
C++ Example to convert char to int using strtol
Let's consider an example to demonstrate the process of converting a character to an integer using the strtol function in C++.
Example
#include <iostream>
#include <cstdlib> // for strtol
using namespace std; //using standard namespace
int main() { //Main Function
const char* str = "123abc";
char* end;
long number = strtol(str, &end, 10);
cout << "Converted number: " << number << endl;
cout << "Remaining string: " << end << endl;
return 0;
}
Output:
Converted number: 123
Remaining string: abc
Explanation
In this instance, we employ the strtol function provided by the C standard library to transform the initial numeric section of a C-style string "123abc" into a long integer. Subsequently, the end pointer indicates the remaining portion of the string ("abc") that was not processed.
Conclusion
In summary, the process of converting a character to an integer in C++ becomes straightforward once we grasp the distinction between ASCII values and numerical characters. Whether our goal is to retrieve the ASCII value, extract individual digits, or transform an entire string into an integer, C++ provides us with numerous approaches to accomplish these tasks.