求助:如何用C语言实现字符到数字的映射转换(附代码片段)
Hey there! Let's get your character-to-digit mapping program working correctly. Your original code has a few critical issues (like uninitialized pointers and misusing strcmp for single characters) so we'll fix those and build out the functionality you need.
Key Issues in Your Original Code
- Uninitialized pointers:
char *test;andchar *result;are wild pointers—writing to them will cause memory errors. We'll use fixed-size arrays instead. - Misusing
strcmp:strcmpcompares entire strings, but you're working with single characters. Just use direct character comparison with==instead. - Incorrect character assignment:
result[i] = "2";uses a string literal (double quotes), but you need a single character (single quotes:'2').
Fixed & Complete Code
#include <stdio.h> #include <string.h> #include <ctype.h> // For toupper() int main() { // Arrays to store input (max 5 chars + null terminator) and result char test[6] = {0}; char result[6] = {0}; int char_count = 0; int input_char; // Read input, limit to 5 alphabetic characters while ((input_char = getchar()) != '\n' && char_count < 5) { // Only process letters, convert to uppercase for consistent checking if (isalpha(input_char)) { test[char_count] = toupper(input_char); char_count++; } } test[char_count] = '\0'; // Ensure input is a valid C string // Map characters to digits based on your rules for (int i = 0; i < char_count; i++) { if (test[i] == 'A' || test[i] == 'B' || test[i] == 'C') { result[i] = '2'; } else if (test[i] == 'D' || test[i] == 'E' || test[i] == 'F') { result[i] = '3'; } // Add more conditions here for other mappings (e.g., G-I → 4, etc.) else { // Fallback for unrecognized characters (adjust as needed) result[i] = '0'; } } result[char_count] = '\0'; // Ensure result is a valid C string // Print the result printf("Input: %s\n", test); printf("Output: %s\n", result); return 0; }
How It Works
- Input Handling: Reads up to 5 alphabetic characters, converts them to uppercase so the mapping works for both lowercase and uppercase inputs.
- Mapping Logic: Directly checks each character against your rules (A-C → 2, D-F → 3). You can easily add more
else ifblocks to extend the mapping (e.g., G-I to 4, J-L to 5, etc.). - Memory Safety: Uses fixed-size arrays instead of wild pointers, so you won't run into unexpected memory access errors.
- Test Case Example: If you input
AFAF, the program will output2323—exactly what you requested!
内容的提问来源于stack exchange,提问作者Test
相关产品推荐
相关产品推荐

