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

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

相关推荐
董先生_ad986ad2 小时前
C# 中的 `lock` 关键字本质
开发语言·c#
元亓亓亓2 小时前
Java后端开发day36--源码解析:HashMap
java·开发语言·数据结构
道剑剑非道3 小时前
QT 打包安装程序【windeployqt.exe】报错c000007d原因:Conda巨坑
开发语言·qt·conda
小邓儿◑.◑3 小时前
C++武功秘籍 | 入门知识点
开发语言·c++
码银5 小时前
Java 集合:泛型、Set 集合及其实现类详解
java·开发语言
大G哥5 小时前
PHP标签+注释+html混写+变量
android·开发语言·前端·html·php
傻啦嘿哟5 小时前
HTTP代理基础:网络新手的入门指南
开发语言·php
fish_study_csdn5 小时前
pytest 技术总结
开发语言·python·pytest
杨筱毅6 小时前
【优秀三方库研读】【C++基础知识】odygrd/quill -- 折叠表达式
c++·三方库研读
曹牧6 小时前
Java 调用webservice接口输出xml自动转义
java·开发语言·javascript