在C ++中,如何将字符串拆分为多个整数?

时间:2013-03-10 16:34:48

标签: c++ arrays string

我有五个值的字符串,每个值用空格分隔。

std::string s = "123 123 123 123 123";

如何将这些分成五个整数的数组?

2 个答案:

答案 0 :(得分:7)

像这样使用std::stringstream

#include <sstream>
#include <string>

...

std::stringstream in(s);
std::vector<int> a;
int temp;
while(in >> temp) {
  a.push_back(temp);
}

答案 1 :(得分:0)

如果您需要内置数组,请尝试此操作,但在一般情况下,通常最好使用之前建议的std::vector。我假设您想要在每个空格字符处拆分字符串。

#include <sstream>
#include <string>
#include <iostream>

int main() {
    std::string s = "123 123 123 123 123";
    std::istringstream iss(s);

    int arr[5];
    for (auto& i : arr) {
        iss >> i;
    }
}
相关问题