[C++] 利用istringstream将字符串按逗号分割

这篇博客介绍了如何使用C++将带逗号的字符串转换为整数向量,通过`istringstream`逐个解析并存储。关键步骤包括替换逗号为空格,然后使用流对象读取并存储每个整数。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

参考:(2条消息) C++分割带逗号的字符串_九霄星河的博客-CSDN博客_c++ 逗号分隔字符串

原理:

第一步:接收字符串 s ;
第二步:遍历字符串 s ,把 s 中的逗号换成空格;
第三步:通过 istringstream 类重新读取字符串 s ;
注意, istringstream 这个类包含在库 < sstream > 中,所以头文件必须包含这个库。

#include<bits/stdc++.h>
#include<sstream>
#include<string>

using namespace std;


int main() {
    vector<int> nums;

    string s = "0,12,123,1234";
    int n = s.size();

    for(int i = 0; i < n; i++) {
        if(s[i] == ',') s[i] = ' ';
    }

    istringstream out(s);
    string str;
    while(out >> str) {
        nums.push_back(stoi(str));
    }

    for(int num:nums) {
        cout<<num<<endl;
    }

    return 0;
}

结果:

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值