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

如何在C++中将"{1,2,3,4,5}"格式的字符串转换为vector<int>

将"{1, 2, 3, 4, 5}"格式输入转为vector的解决方案

你遇到的编译错误是因为C++标准库没有为std::vector<int>和std::istream重载>>运算符,直接用cin >> vector的写法编译器无法识别。错误信息翻译如下:

./main.cpp:124:9: 错误:二元表达式的操作数无效('std::istream'(别名 'basic_istream<char>')和 'vector<int>')
    cin >> user_input;

要处理这种带花括号和逗号分隔的输入格式,需要手动解析内容,以下是两种可行的实现方式:


方法一:流式直接解析

这种方法适合从标准输入直接读取格式为{1, 2, 3, 4, 5}的内容,逐字符处理分隔符:

#include <iostream>
#include <vector>

using namespace std;

int main() {
    vector<int> input;
    char delimiter;

    // 读取开头的左花括号
    cin >> delimiter;
    if (delimiter != '{') {
        cerr << "输入格式错误:缺少起始的'{" << endl;
        return 1;
    }

    int num;
    // 循环读取整数
    while (cin >> num) {
        input.push_back(num);
        // 读取逗号或右花括号
        cin >> delimiter;
        if (delimiter == '}') {
            break;
        } else if (delimiter != ',') {
            cerr << "输入格式错误:预期逗号或'}',实际得到 " << delimiter << endl;
            return 1;
        }
    }

    // 验证结果(可选)
    for (int n : input) {
        cout << n << " ";
    }
    cout << endl;
    return 0;
}

方法二:先读字符串再分割

如果输入是完整的格式字符串(比如已经把{1, 2, 3, 4, 5}存为std::string),可以先去除首尾花括号,再按逗号分割转换:

#include <iostream>
#include <vector>
#include <string>
#include <sstream>
#include <algorithm>

using namespace std;

int main() {
    string input_str;
    cin >> input_str;

    // 移除首尾的花括号
    if (!input_str.empty()) {
        if (input_str.front() == '{') input_str.erase(input_str.begin());
        if (input_str.back() == '}') input_str.pop_back();
    }

    vector<int> input;
    stringstream ss(input_str);
    string token;

    // 按逗号分割字符串
    while (getline(ss, token, ',')) {
        // 移除token中的空格
        token.erase(remove(token.begin(), token.end(), ' '), token.end());
        if (!token.empty()) {
            input.push_back(stoi(token));
        }
    }

    // 验证结果(可选)
    for (int n : input) {
        cout << n << " ";
    }
    cout << endl;
    return 0;
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.05 23:40:19