C++ Program To Find Ascii Code For Charactersnumbers And Symbols
Understanding character encodings is fundamental in computing. The ASCII (American Standard Code for Information Interchange) standard assigns unique numerical values to characters, numbers, and symbols, enabling computers to store and process text.
In this article, you will learn how to write C++ programs to find the ASCII code for various characters, numbers, and symbols.
Problem Statement
When working with text data, especially in system programming, data transmission, or cryptography, it is often necessary to know the underlying numerical representation of characters. Directly converting a character to its integer equivalent helps in tasks like character manipulation, validation, or understanding how data is stored. The problem is to efficiently obtain these integer (ASCII) values in C++.
Example
Consider the character 'A'. Its ASCII code is 65. Similarly, the character '5' has an ASCII code of 53, and the symbol '$' has an ASCII code of 36. A C++ program can easily display these values.
Background & Knowledge Prerequisites
To follow this article, a basic understanding of C++ programming is helpful, including:
- Variables and Data Types: Specifically
charandint. - Input/Output Operations: Using
coutandcin. - Type Casting: Converting one data type to another.
No special libraries or complex setups are required beyond a standard C++ compiler.
Use Cases or Case Studies
Understanding and obtaining ASCII codes has several practical applications:
- Character Validation: Checking if an input character falls within a specific range (e.g., 'a'-'z' for lowercase letters).
- Simple Encryption/Decryption: Performing Caesar cipher-like shifts by adding or subtracting from ASCII values.
- String Manipulation: Converting characters between uppercase and lowercase using their ASCII offsets.
- Data Transmission: In low-level network protocols, characters might be sent or received as their byte (ASCII) values.
- Hash Function Development: ASCII values can be used as building blocks for simple hashing algorithms.
Solution Approaches
C++ provides a straightforward way to obtain the ASCII value of a character through implicit or explicit type casting. Since char is an integral type, it can be easily converted to an int.
Approach 1: Using Type Casting for a Single Character
This approach demonstrates how to find the ASCII code of a predefined character using explicit type casting.
// ASCII Code for Predefined Character
#include <iostream>
using namespace std;
int main() {
// Step 1: Declare a character variable.
char myChar = 'C';
// Step 2: Explicitly cast the character to an integer to get its ASCII value.
int asciiValue = static_cast<int>(myChar);
// Step 3: Print the character and its ASCII value.
cout << "The ASCII code for character '" << myChar << "' is: " << asciiValue << endl;
// Repeat for a number character
char numChar = '7';
int numAsciiValue = static_cast<int>(numChar);
cout << "The ASCII code for character '" << numChar << "' is: " << numAsciiValue << endl;
// Repeat for a symbol character
char symbolChar = '#';
int symbolAsciiValue = static_cast<int>(symbolChar);
cout << "The ASCII code for character '" << symbolChar << "' is: " << symbolAsciiValue << endl;
return 0;
}
Sample Output:
The ASCII code for character 'C' is: 67
The ASCII code for character '7' is: 55
The ASCII code for character '#' is: 35
Stepwise Explanation:
- A
charvariable,myChar, is declared and initialized with the character 'C'. static_castexplicitly converts the(myChar) charto anint. The C++ compiler interprets thechar's internal numerical representation (its ASCII value) as an integer.- The
coutstatement then prints both the character and its derived ASCII value. The process is repeated for a number character ('7') and a symbol character ('#').
Approach 2: Getting Input from the User
This approach extends the first by allowing the user to input a character, whose ASCII code is then displayed.
// ASCII Code for User Input Character
#include <iostream>
using namespace std;
int main() {
// Step 1: Declare a character variable to store user input.
char inputChar;
// Step 2: Prompt the user to enter a character.
cout << "Enter a character (letter, number, or symbol): ";
cin >> inputChar;
// Step 3: Implicitly convert the character to an integer for its ASCII value.
// When a char is used in an arithmetic context or assigned to an int,
// it implicitly converts to its integer (ASCII) value.
int asciiValue = inputChar;
// Step 4: Print the character and its ASCII value.
cout << "The ASCII code for '" << inputChar << "' is: " << asciiValue << endl;
return 0;
}
Sample Output (User enters 'k'):
Enter a character (letter, number, or symbol): k
The ASCII code for 'k' is: 107
Stepwise Explanation:
- A
charvariableinputCharis declared to hold the user's input. - The program prompts the user to enter a character using
cout. cin >> inputChar;reads a single character from the console and stores it ininputChar.int asciiValue = inputChar;demonstrates implicit type conversion. When acharis assigned to anint, C++ automatically converts thechar's ASCII value to an integer. Explicit casting (static_cast) would yield the same result.(inputChar) - The character and its ASCII value are printed.
Approach 3: Finding ASCII Codes for Characters in a String
This method shows how to iterate through a string and find the ASCII code for each character within it.
// ASCII Codes for Characters in a String
#include <iostream>
#include <string> // Required for std::string
using namespace std;
int main() {
// Step 1: Declare a string variable.
string myString = "Hello World! 123";
// Step 2: Loop through each character in the string.
cout << "ASCII codes for each character in \\"" << myString << "\\":" << endl;
for (char c : myString) {
// Step 3: Convert each character to its ASCII value.
// Implicit conversion is used here.
int asciiValue = c;
// Step 4: Print the character and its ASCII value.
cout << "'" << c << "' : " << asciiValue << endl;
}
return 0;
}
Sample Output:
ASCII codes for each character in "Hello World! 123":
'H' : 72
'e' : 101
'l' : 108
'l' : 108
'o' : 111
' ' : 32
'W' : 87
'o' : 111
'r' : 114
'l' : 108
'd' : 100
'!' : 33
' ' : 32
'1' : 49
'2' : 50
'3' : 51
Stepwise Explanation:
- A
std::stringvariablemyStringis initialized with a sample text. - A range-based
forloop (for (char c : myString)) iterates through each charactercin themyString. - Inside the loop,
int asciiValue = c;implicitly converts the current charactercto its integer (ASCII) value. - Both the character and its ASCII value are printed for each character in the string.
Conclusion
Finding the ASCII code of a character in C++ is a straightforward process, primarily leveraging the implicit or explicit type casting between char and int data types. This fundamental capability is vital for various programming tasks, from basic character manipulation to more complex data processing and security applications. By understanding how characters map to their numerical representations, you gain a deeper insight into how computers handle text data.
Summary
- ASCII (American Standard Code for Information Interchange) provides numerical codes for characters, numbers, and symbols.
- In C++, a
chardata type is an integral type and can be easily converted to anintto obtain its ASCII value. - Type Casting:
- Explicit Casting: Use
static_castfor clarity.(charVariable) - Implicit Casting: Assigning a
charto anintvariable (int ascii = charVariable;) automatically performs the conversion. - This technique is useful for character validation, simple encryption, string manipulation, and low-level data handling.
- You can find ASCII codes for predefined characters, user input, or iterate through strings to get values for multiple characters.