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

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

相关推荐
是个西兰花4 小时前
Linux:深入解析Linux线程原理与实现
linux·运维·c++·线程·互斥锁
多加点辣也没关系5 小时前
JavaScript|第24章:事件循环与并发模型
开发语言·javascript·ecmascript
ん贤5 小时前
怎么设计,才算一个优秀审计模块
大数据·开发语言·设计·审计
l1t5 小时前
测试用rust重写的postgresql: pgrust
开发语言·postgresql·rust
2501_948106915 小时前
计算机毕业设计之jsp-智慧旅游分享平台
java·开发语言·spark·汽车·课程设计·旅游
阿里云云原生6 小时前
Agent 不再是“玩具”!AgentScope Java 2.0 GA 发布:构建企业级分布式智能体底座
java·开发语言·分布式·agentscope
BIM云平台开发6 小时前
【App.vue里跟踪页面跳转和用户ID】
开发语言·前端·javascript
NiceCloud喜云6 小时前
ClaudeAPI 接入 n8n / Dify / Open WebUI 实战:Base URL 配置、调用示例与排错
开发语言·ai·chatgpt·aigc
小保CPP6 小时前
OCR C++ Tesseract基础用法
c++·人工智能·ocr·模式识别·光学字符识别
庵中十三居士6 小时前
【纯AI无人工修改】AI Agent从0到1实战:50行Python手写核心循环,一次看懂所有Agent框架的底层逻辑
开发语言·人工智能·python