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

C++字符数组提取数字函数返回无关数值求助

解决从char数组提取数字时输出ASCII码值的问题

Hey there! Let's break down why you're seeing values like 48, 49, 50 instead of the actual numbers you want, and fix the function to extract multiple numbers (including decimals) correctly.

问题根源分析

The values 48, 49, 51 are the ASCII codes for the characters '0', '1', '3' respectively. This means your code is likely outputting the raw ASCII value of the character instead of converting it to its numeric equivalent. Additionally, your current function returns a single double, but you need to extract multiple numbers from the input string—so we'll need to adjust the return type to hold multiple values.

修正后的实现思路

To extract all numbers (integers and decimals) from the char array:

  • Traverse the input string, skipping non-numeric characters (except for a single decimal point per number).
  • When we hit a valid start of a number (digit or first decimal point), track the substring until we hit an invalid character.
  • Convert that substring to a double and add it to our result list.
  • Continue traversing until the end of the string.

完整代码示例

#include <iostream>
#include <vector>
#include <string>
#include <cctype>

using namespace std;

vector<double> ExtractNumbersFromString(char* str) {
    vector<double> numbers;
    string currentNumber;
    bool hasDecimal = false;

    for (int i = 0; str[i] != '\0'; ++i) {
        // 检查当前字符是否为数字
        if (isdigit(str[i])) {
            currentNumber += str[i];
        }
        // 检查是否为小数点,且当前数字尚未包含小数点
        else if (str[i] == '.' && !hasDecimal) {
            currentNumber += str[i];
            hasDecimal = true;
        }
        // 遇到非有效字符且当前正在构建数字时,完成转换并保存
        else if (!currentNumber.empty()) {
            numbers.push_back(stod(currentNumber));
            // 重置状态以处理下一个数字
            currentNumber.clear();
            hasDecimal = false;
        }
    }

    // 处理字符串末尾可能残留的数字
    if (!currentNumber.empty()) {
        numbers.push_back(stod(currentNumber));
    }

    return numbers;
}

int main() {
    char input[] = "141923adsfab321221.222";
    vector<double> result = ExtractNumbersFromString(input);

    cout << "提取到的数字:" << endl;
    for (double num : result) {
        cout << num << endl;
    }

    return 0;
}

代码解释

  • vector<double> 返回值: 支持存储多个提取到的数字,满足你一次性获取所有目标数值的需求。
  • currentNumber 字符串: 逐步构建当前正在提取的数字子串,确保能处理多位数和带小数的情况。
  • hasDecimal 标记: 避免单个数字中出现多个小数点,防止生成123..45这类无效数值。
  • isdigit() 检查: 安全识别数字字符,避免误处理其他符号。
  • stod() 函数: 将构建好的数字字符串转换为double类型,同时兼容整数和小数的转换。

测试输出

对于输入 "141923adsfab321221.222",代码会输出:

141923
321221.222

针对你原代码的提示

如果你之前直接输出字符(比如cout << str[i];),就会打印字符的ASCII值而非数字本身。单个字符转数字可以用str[i] - '0'(因为ASCII中数字字符是连续排列的),但对于完整的多位数或小数,构建子串再转换是更可靠的方案。

内容的提问来源于stack exchange,提问作者Huan

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.25 06:55:56