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

发布于:2025-03-23 ⋅ 阅读:(18) ⋅ 点赞:(0)

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

1. 分割成字符串数组

#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. 分割成整型数组

#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

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