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

C++中数字字符串转int存入vector时stoi匹配错误问题

问题分析与修复方案

错误原因

  1. stoi参数不匹配:stoi函数的参数要求是字符串(const string&)或C风格字符串(const char*),但你传入的num[i]是单个char类型,编译器找不到对应的函数重载,因此报错。
  2. 循环边界越界:i <= num.length()会导致访问num[num.length()],而字符串的有效索引范围是0到num.length()-1,这会触发未定义行为。

修复后的代码

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

int main() {
    vector<int> vec;
    string num;
    cin >> num;
    for(int i = 0; i < num.length(); i++){
        // 利用ASCII码特性直接将字符数字转为整数
        vec.push_back(num[i] - '0');
    }
    // 可选:打印vector验证结果
    for(int n : vec){
        cout << n << " ";
    }
    return 0;
}

关键修改说明

  • 替换stoi(num[i])为num[i] - '0':ASCII表中字符'0'到'9'的编码是连续递增的,用字符数字减去'0'的ASCII值,就能直接得到对应的整数,这种方式比调用stoi更高效简洁。
  • 修正循环条件为i < num.length():确保只遍历字符串的有效索引,避免越界访问。

备选方案(若坚持用stoi)

如果一定要通过stoi实现,需要将单个字符转换为字符串后传入:

vec.push_back(stoi(string(1, num[i])));

但这种方式冗余,不推荐使用。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.06 02:16:14