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

如何将逗号分隔的字符串元素转换为int数组?(含异常排查)

问题分析与修复方案

嘿,看你遇到的解析问题挺典型的——带末尾逗号的字符串直接乱掉,多位数还被拆成单个数字,这明显是你的解析逻辑有几个关键漏洞,咱们一个个捋清楚:

你的代码里的核心问题

  • 越界访问+错误字符选取:你用了string[j-2],这在j=0或1的时候会变成负数索引,直接踩了字符串外的内存,完全是逻辑跑偏。而且你应该收集当前的数字字符,不是往前跳两位的字符啊。
  • 没处理多位数:比如"13"是两个字符,你的代码只取了其中一个(还取错位置),这就是为啥示例里的13变成3、14变成4、22变成2的原因。
  • 误用putchar:putchar是用来往控制台输出字符的,它返回的是输出字符的ASCII值,根本不是把字符转成数字的方法。要把字符'5'转成整数5,得用string[j] - '0'才对。
  • 未处理末尾逗号/空数字:字符串结尾是逗号时,你的代码会在最后一次循环尝试读取不存在的数字,直接导致奇怪的输出。

修复后的代码实现

正确的思路应该是:遍历字符串,收集连续的数字字符,遇到逗号(或字符串结束)时,把收集到的数字转成整数存入数组,同时跳过空的数字(比如末尾逗号的情况)。

如果你想用灵活的动态数组(推荐),可以这么写:

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

using namespace std;

int main() {
    string input = "5,6,13,4,14,22,";
    vector<int> numArray;
    string currentNum;

    for (char c : input) {
        if (c == ',') {
            if (!currentNum.empty()) { // 跳过末尾逗号带来的空数字
                numArray.push_back(stoi(currentNum));
                currentNum.clear();
            }
        } else {
            currentNum += c; // 持续收集数字字符
        }
    }

    // 验证输出
    cout << "解析后的数组:";
    for (int num : numArray) {
        cout << num << " ";
    }
    cout << endl;

    return 0;
}

如果一定要用固定大小的int数组(假设你确定输入的数字数量),可以调整成这样:

#include <iostream>
#include <string>

using namespace std;

int main() {
    string input = "5,6,13,4,14,22,";
    int numArray[6]; // 提前确定数组大小
    int nr = 0;
    string currentNum;

    for (char c : input) {
        if (c == ',') {
            if (!currentNum.empty() && nr < 6) { // 避免数组越界
                numArray[nr++] = stoi(currentNum);
                currentNum.clear();
            }
        } else {
            currentNum += c;
        }
    }

    // 验证输出
    cout << "解析后的数组:";
    for (int i = 0; i < nr; i++) {
        cout << numArray[i] << " ";
    }
    cout << endl;

    return 0;
}

测试结果

  • 输入"5,6,13,4,14,22,"时,输出:5 6 13 4 14 22
  • 输入"2,3,5,1,6,4"时,输出:2 3 5 1 6 4

完全符合你的预期~

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.15 08:30:05