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

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

相关推荐
saltymilk6 小时前
C++ 模板参数推导问题小记(模板类的模板构造函数)
c++·模板元编程
感哥6 小时前
C++ lambda 匿名函数
c++
沐怡旸12 小时前
【底层机制】std::unique_ptr 解决的痛点?是什么?如何实现?怎么正确使用?
c++·面试
感哥12 小时前
C++ 内存管理
c++
博笙困了19 小时前
AcWing学习——双指针算法
c++·算法
感哥19 小时前
C++ 指针和引用
c++
感哥1 天前
C++ 多态
c++
沐怡旸2 天前
【底层机制】std::string 解决的痛点?是什么?怎么实现的?怎么正确用?
c++·面试
River4162 天前
Javer 学 c++(十三):引用篇
c++·后端
感哥2 天前
C++ std::set
c++