c++怎么将输入的一行字符根据“,“分割成字符串数组或者整型数组

在C++中,可以使用标准库中的std::stringstd::istringstream来将输入的一行字符根据逗号,分割成字符串数组或整型数组。以下是一个示例代码:

1. 分割成字符串数组

cpp 复制代码
#include <iostream>
#include <sstream>
#include <vector>
#include <string>

int main() {
    std::string input;
    std::cout << "请输入一行以逗号分隔的字符串: ";
    std::getline(std::cin, input);

    std::vector<std::string> result;
    std::istringstream iss(input);
    std::string token;

    while (std::getline(iss, token, ',')) {
        result.push_back(token);
    }

    std::cout << "分割后的字符串数组: " << std::endl;
    for (const auto& str : result) {
        std::cout << str << std::endl;
    }

    return 0;
}

2. 分割成整型数组

cpp 复制代码
#include <iostream>
#include <sstream>
#include <vector>
#include <string>

int main() {
    std::string input;
    std::cout << "请输入一行以逗号分隔的整数: ";
    std::getline(std::cin, input);

    std::vector<int> result;
    std::istringstream iss(input);
    std::string token;

    while (std::getline(iss, token, ',')) {
        result.push_back(std::stoi(token));
    }

    std::cout << "分割后的整型数组: " << std::endl;
    for (const auto& num : result) {
        std::cout << num << std::endl;
    }

    return 0;
}

代码说明:

  1. std::getline(std::cin, input): 从标准输入读取一行字符串。
  2. std::istringstream iss(input): 将输入的字符串转换为一个字符串流。
  3. std::getline(iss, token, ','): 从字符串流中读取以逗号分隔的每个子字符串。
  4. std::stoi(token): 将字符串转换为整数(仅用于整型数组的情况)。

示例输入输出:

字符串数组:

输入:

复制代码
apple,banana,cherry

输出:

复制代码
分割后的字符串数组: 
apple
banana
cherry
整型数组:

输入:

复制代码
1,2,3,4,5

输出:

复制代码
分割后的整型数组: 
1
2
3
4
5

通过这种方式,你可以轻松地将输入的字符串根据逗号分割成字符串数组或整型数组。

相关推荐
神里流~霜灭5 分钟前
蓝桥备赛指南(8):矩阵基础
c语言·数据结构·c++·算法·矩阵·排序算法
AWS官方合作商17 分钟前
WebGPU实战:Three.js性能优化新纪元
服务器·开发语言·javascript
红豆和绿豆31 分钟前
Netty和Project Reactor如何共同处理大数据流?
java·开发语言·网络
汪宁宇1 小时前
qt中libusb热插拔检测示例代码
开发语言·c++·qt·libusb
神里流~霜灭1 小时前
数据结构:树的先序遍历、中序遍历、后序遍历和层序遍历
c语言·数据结构·c++·算法·二叉树·
起个破名想半天了1 小时前
Matlab2024a免费版下载教程
开发语言·matlab·下载教程
AaronZZH1 小时前
【基础】Windows 中通过 VSCode 使用 GCC 编译调试 C++
c++·windows·vscode
小白教程1 小时前
python人脸检测、人脸识别、活体检测入门学习教程
开发语言·python·人脸识别·人脸检测·活体检测·活体认证·python人脸识别
愚戏师1 小时前
C++ :顺序容器
开发语言·c++·rpc
冷琴19961 小时前
基于python+django的图书借阅网站-图书借阅管理系统源码+运行步骤
开发语言·python·django