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

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

相关推荐
铭哥的编程日记18 分钟前
《C++ string 完全指南:string的模拟实现》
c++
钟离墨笺21 分钟前
Go 语言-->指针
开发语言·后端·golang
Yu_Lijing25 分钟前
MySQL进阶学习与初阶复习第二天
数据库·c++·学习·mysql
超浪的晨1 小时前
Java 代理机制详解:从静态代理到动态代理,彻底掌握代理模式的原理与实战
java·开发语言·后端·学习·代理模式·个人开发
l1t1 小时前
开源嵌入式数组引擎TileDB的简单使用
c语言·数据库·c++
咖啡の猫1 小时前
bash的特性-bash中的引号
开发语言·chrome·bash
java叶新东老师1 小时前
idea提交时忽略.class、.iml文件和文件夹或目录的方法
java·开发语言
走过,莫回头1 小时前
在OpenMP中,#pragma omp的使用
开发语言·openmp
Warren982 小时前
Java Collections工具类
java·开发语言·笔记·python·学习·oracle·硬件工程
工程师0072 小时前
C#多线程,同步与异步详解
开发语言·c#·多线程·同步·异步编程