Find the ASCII value of a character in C++
In this tutorial, we will learn the process to find the ASCII value of a character in C++ programming.
The name ASCII stands for American Standard Code for Information Interchange. It is a character encoding technique that we use for electronic communicating purposes as well as for representing text in computers. Each character or number has a unique ASCII value of its own, which ranges from 0 to 127.
Before proceeding to the solution, let us understand the problem first.
To understand this problem, let us consider a simple example.
For example, take a which has the ASCII value 97. This means that if we assign ‘a’ to a character variable, then the character variable holds the ASCII value rather than the character itself. To find the ASCII value of a given character in C++, we can use the int() function.
Program to find ASCII value of a character in C++
The program illustrates how to find the ASCII value of a character, number, special character as well as ASCII value range for ‘a’ to ‘z’, ‘A’ to ‘Z’ and ‘0’ to ‘9’ respectively. It uses the int() function, which accepts one parameter of a type character, and shows how to pass the argument in the form of a character or a character variable.
#include <iostream> using namespace std; int main() { char ch1='a'; char ch2='5'; char ch3='$'; char ch4=' '; cout<<"ASCII value range of 'a' to 'z' is: "<<int('a')<<" - "<<int('z')<<endl; cout<<"ASCII value range of 'A' to 'Z' is: "<<int('A')<<" - "<<int('Z')<<endl; cout<<"ASCII value range of '0' to '9' is: "<<int('0')<<" - "<<int('9')<<endl; cout<<"ASCII value of 'a' is: "<<int(ch1)<<endl; cout<<"ASCII value of '5' is: "<<int(ch2)<<endl; cout<<"ASCII value of '$' is: "<<int(ch3)<<endl; cout<<"ASCII value of space is: "<<int(ch4)<<endl; return 0; }
Output :
ASCII value range of 'a' to 'z' is: 97 - 122 ASCII value range of 'A' to 'Z' is: 65 - 90 ASCII value range of 'a' to 'z' is: 48 - 57 ASCII value of 'a' is: 97 ASCII value of '5' is: 53 ASCII value of '$' is: 36 ASCII value of space is: 32
Thank you for reading. Keep learning!
Recommended article: Removing the Last Line from a Text File in C++
Leave a Reply