You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何将字符转换为数值不变的整数?及C语言提取输入字符串中数字转为整数的代码问题求助

Solutions to Your C Programming Questions

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. Use fgets() instead.
  • Incorrect use of atoi(): atoi() expects a pointer to a null-terminated string (const char*), but you're passing a single char (sir[i]). This causes undefined behavior because atoi() 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 1 then 9), 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

  1. Replaced gets() with fgets(): fgets() is safe because it takes the buffer size as an argument, preventing overflow.
  2. Removed newline character: fgets() includes the newline character when the user presses Enter. We use strcspn() to find the newline and replace it with a null terminator.
  3. Built the integer incrementally: Instead of printing each digit, we start with result = 0 and update it with result = result * 10 + (digit). For "19":
    • First digit '1': 0 *10 +1 =1
    • Second digit '9': 1*10 +9=19
  4. Standard int main(): Using int main() and returning 0 is compliant with the C standard (instead of void 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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.27 13:27:44