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

在C++中如何将包含数字列表的字符串转换为数值数组?

错误原因分析
  • 数组定义非法:char A[] = {} 属于零长度数组,C++标准不支持该语法,即使部分编译器兼容扩展,也没有预留存储空间,后续写入元素会触发数组越界,属于未定义行为。
  • 字符串赋值语法错误:string line1 = [1, 2, 3]; 中字符串字面量需要用双引号包裹,正确写法应为string line1 = "[1, 2, 3]";,原写法会直接触发编译错误。
  • 字符未转成数值:当前逻辑提取的是字符型的'1'、'2',对应的ASCII码值分别是49、50,和需要的数值1、2不一致,需要做字符到数值的转换。
  • 不支持多位数场景:如果待处理字符串里存在两位及以上的数字(比如[12, 34, 56]),当前逻辑会把每一位字符单独拆分存储,无法得到完整的数字值。
正确实现方法

简易版(适配单数字测试场景)

适合你当前的[1, 2, 3]测试用例,逻辑和你原代码对齐:

#include <iostream>
#include <string>
using namespace std;

int main() {
    // 提前预留足够的数组存储空间,也可改用vector<int>避免手动预估长度
    int A[10] = {0};
    short loop = 0;
    string line1 = "[1, 2, 3]";
    for(int i = 0 ; i < line1.length(); i++){
        if(line1[i] == '[' || line1[i] == ',' || line1[i] == ' '|| line1[i] == ']')
            continue;
        else{
            // 减去字符'0'的ASCII码值,完成字符到数字的转换
            A[loop] = line1[i] - '0';
            loop++;
        }
    }
    // 验证输出
    for(int i=0; i<loop; i++){
        cout << A[i] << " ";
    }
    return 0;
}

通用版(支持多位数、正负整数)

使用vector动态存储,无需提前预估数组长度,适配更复杂的输入场景:

#include <iostream>
#include <string>
#include <vector>
#include <cctype>
using namespace std;

int main() {
    vector<int> nums;
    string line1 = "[1, 23, -45, 678]";
    int current_num = 0;
    bool is_num = false;
    bool is_negative = false;

    for(int i = 0; i < line1.size(); i++) {
        char c = line1[i];
        if(isdigit(c)) {
            is_num = true;
            current_num = current_num * 10 + (c - '0');
        } else if(c == '-') {
            is_negative = true;
        } else if(c == ',' || c == ']') {
            if(is_num) {
                if(is_negative) current_num = -current_num;
                nums.push_back(current_num);
                // 重置状态位
                current_num = 0;
                is_num = false;
                is_negative = false;
            }
        }
        // 空格、[等无意义字符直接跳过
    }
    // 验证输出
    for(int num : nums) {
        cout << num << " ";
    }
    return 0;
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.02 22:30:01