C++ Program To Convert Letters Into A Phone Number
When converting letters to a phone number, you translate alphabetic characters into their corresponding numeric digits based on the standard phone keypad layout. In this article, you will learn how to implement a C++ program that takes a string containing letters and converts it into a sequence of digits, similar to how older phones would map names to numbers.
Problem Statement
The challenge is to develop a C++ program that processes an input string, which may contain uppercase or lowercase letters, and converts these letters into their equivalent digits as found on a phone keypad. Non-alphabetic characters (like spaces, hyphens, or existing digits) should be preserved without alteration. This conversion is useful for remembering numbers associated with names or for specific data processing tasks.
Example
Consider the input string "HELLO WORLD". The program should produce the output "43556 96753".
Background & Knowledge Prerequisites
To understand and implement this solution, you should have a basic understanding of:
- C++ Fundamentals: Variables, data types, input/output operations.
- String Manipulation: Working with
std::stringobjects, iterating through characters. - Conditional Statements:
if-else iforswitchstatements for character mapping. - Loops:
fororwhileloops for processing each character in the string.
Relevant headers for this task typically include for input/output and for string manipulation. The header can be useful for character manipulation functions like toupper().
Use Cases or Case Studies
Converting letters to phone numbers has several practical applications:
- Vanity Phone Numbers: Companies often use letters to create memorable phone numbers (e.g., 1-800-FLOWERS). This program can help translate such numbers back to digits.
- Data Entry and Validation: In systems where users might type letters instead of digits for phone numbers, this conversion can standardize input.
- Historical Data Processing: Analyzing old phone books or directories where names were sometimes associated with numbers by mapping letters.
- Educational Tools: Demonstrating basic character processing and string manipulation concepts in programming.
- Game Development: Simple puzzles or code-breaking games that involve converting text to numbers.
Solution Approaches
For this problem, the most direct approach involves iterating through the input string and, for each character, applying a mapping rule to convert letters to digits. The primary variations lie in how this mapping is implemented. We will detail a robust approach using switch statements.
Approach 1: Character Mapping using switch Statement
This approach iterates through each character of the input string. If the character is a letter, it converts it to its uppercase equivalent (to simplify mapping) and then uses a switch statement to assign the corresponding digit. Non-alphabetic characters are appended directly to the result.
One-line summary: Iterate through the input string, converting letters to their phone keypad digits using a switch statement, while preserving other characters.
// Convert Letters to Phone Number
#include <iostream> // For input/output operations (cin, cout)
#include <string> // For using std::string
#include <cctype> // For toupper() function
int main() {
// Step 1: Declare a string to store the input and another for the result.
std::string inputString;
std::string phoneNumber = "";
// Step 2: Prompt the user to enter a string.
std::cout << "Enter a string (e.g., HELLO WORLD): ";
std::getline(std::cin, inputString); // Use getline to read entire line with spaces
// Step 3: Iterate through each character of the input string.
for (char c : inputString) {
// Step 4: Convert the character to uppercase to simplify mapping.
char upperC = std::toupper(c);
// Step 5: Use a switch statement to map letters to digits.
switch (upperC) {
case 'A': case 'B': case 'C':
phoneNumber += '2';
break;
case 'D': case 'E': case 'F':
phoneNumber += '3';
break;
case 'G': case 'H': case 'I':
phoneNumber += '4';
break;
case 'J': case 'K': case 'L':
phoneNumber += '5';
break;
case 'M': case 'N': case 'O':
phoneNumber += '6';
break;
case 'P': case 'Q': case 'R': case 'S':
phoneNumber += '7';
break;
case 'T': case 'U': case 'V':
phoneNumber += '8';
break;
case 'W': case 'X': case 'Y': case 'Z':
phoneNumber += '9';
break;
default: // If it's not a letter, append it as is.
phoneNumber += c;
break;
}
}
// Step 6: Display the converted phone number.
std::cout << "Converted Phone Number: " << phoneNumber << std::endl;
return 0;
}
Sample Output:
Enter a string (e.g., HELLO WORLD): CALL ME 555-GET-HELP
Converted Phone Number: 2255 63 555-438-4357
Stepwise Explanation:
- Include Headers: We include
for console input/output,forstd::string, andforstd::toupper. - Declare Variables:
inputStringstores the user's input, andphoneNumberwill build the resulting digit string. - Get User Input:
std::getline(std::cin, inputString)reads an entire line of text, including spaces, from the user. - Iterate Through String: A
forloop iterates through eachchar cin theinputString. - Convert to Uppercase:
std::toupper(c)converts the current charactercto its uppercase equivalent. This simplifies theswitchstatement, as we only need to check for uppercase letters. - Character Mapping:
- A
switchstatement checks theupperCcharacter.
- A
case labels are grouped for letters that map to the same digit (e.g., 'A', 'B', 'C' all map to '2').phoneNumber string using phoneNumber += 'digit'.break statement exits the switch after a match.default case handles any characters that are not letters (numbers, symbols, spaces), appending them directly to phoneNumber without conversion.- Display Result: Finally, the program prints the
phoneNumberstring to the console.
Conclusion
Converting letters to phone numbers is a common programming exercise that demonstrates fundamental string manipulation and conditional logic in C++. By iterating through a string and applying character-to-digit mapping, you can effectively translate alphabetic inputs into their numeric phone keypad equivalents. The switch statement provides a clean and readable way to implement this mapping logic.
Summary
- The goal is to translate letters in a string to phone keypad digits, preserving non-alphabetic characters.
- Essential C++ knowledge includes string handling, loops, and conditional statements (
switchorif-else). - The
std::toupper()function simplifies character mapping by standardizing input to uppercase. - A
forloop iterates through the string, and aswitchstatement handles the letter-to-digit conversion. - Non-alphabetic characters are passed through unchanged via the
defaultcase in theswitchstatement. - This functionality is useful for vanity numbers, data standardization, and educational examples.