如何将字符转换为数值不变的整数?及C语言提取输入字符串中数字转为整数的代码问题求助
Hey Roberta, let's work through your two C programming questions and fix your code to get the result you want!
1. Converting a Single Char to an Int (Preserving Numeric Value)
The simplest and most efficient way to convert a single numeric character to its corresponding integer is to use the ASCII value difference.
In ASCII, the characters '0' to '9' are consecutive: '0' has an ASCII value of 48, '1' is 49, ..., '9' is 57. So if you subtract the ASCII value of '0' from any numeric character, you'll get the integer equivalent directly:
char c = '5'; int num = c - '0'; // num will be 5
This works because '5' - '0' translates to 53 - 48 = 5 in integer arithmetic. No need for functions like atoi() here—those are designed for converting entire strings, not single characters.
2. Extracting Numeric Characters from a String and Converting to an Integer
Your current code has a few key issues that are preventing it from working correctly. Let's break down the problems and fix them:
Issues in Your Original Code
- Unsafe
gets()function:gets()is deprecated in C because it doesn't check buffer boundaries, leading to potential buffer overflows. Usefgets()instead. - Incorrect use of
atoi():atoi()expects a pointer to a null-terminated string (const char*), but you're passing a singlechar(sir[i]). This causes undefined behavior becauseatoi()will read memory beyond the single character, resulting in garbage values. - No handling for consecutive digits: Your code prints each digit individually (e.g., for "19" it would print
1then9), but you want to combine them into a single integer (19).
Fixed Code
Here's a corrected version of your code that addresses all these issues:
#define _CRT_SECURE_NO_WARNINGS #include <stdio.h> #include <string.h> // For strcspn() to handle newline from fgets() int main() { // Use int main() instead of void main() for standard compliance char sir[20]; int i = 0; int result = 0; // Variable to accumulate the numeric value printf("Introduceti varsta sub forma - Eu am X ani. - : "); // Use fgets instead of gets() fgets(sir, sizeof(sir), stdin); // Remove the trailing newline character added by fgets() sir[strcspn(sir, "\n")] = '\0'; while (sir[i] != '\0') { if (sir[i] >= '0' && sir[i] <= '9') { // Convert char to int and build the full number result = result * 10 + (sir[i] - '0'); } i++; } // Print the final integer result printf("%d\n", result); return 0; // Return 0 to indicate successful execution }
Key Improvements Explained
- Replaced
gets()withfgets():fgets()is safe because it takes the buffer size as an argument, preventing overflow. - Removed newline character:
fgets()includes the newline character when the user presses Enter. We usestrcspn()to find the newline and replace it with a null terminator. - Built the integer incrementally: Instead of printing each digit, we start with
result = 0and update it withresult = result * 10 + (digit). For "19":- First digit '1':
0 *10 +1 =1 - Second digit '9':
1*10 +9=19
- First digit '1':
- Standard
int main(): Usingint main()and returning 0 is compliant with the C standard (instead ofvoid main()which is non-standard in some compilers).
Testing this code with your example input "I am 19 years old" will output 19 as an integer, exactly what you need!
内容的提问来源于stack exchange,提问作者Roberta Antal

