2

I have string s = "4 99 34 56 28";

I need to split this string to the array: [4, 99, 34, 56, 28]

I do it in java:

String line = reader.readLine();
String[] digits = line.split(" ");

But how can I do it in C++? without external libraries.

ip696
  • 6,574
  • 12
  • 65
  • 128

1 Answers1

1

Split the string by spaces, and for every token (number in your case), convert the string to an int, like this:

#include <vector>
#include <string>
#include <sstream>
#include <iostream>
#include <string> // stoi

using namespace std;

int main(void)
{
    string s("4 99 34 56 28");
    string buf;      
    stringstream ss(s); 

    vector<int> tokens;

    while (ss >> buf)
        tokens.push_back(stoi(buf));

    for(unsigned int i = 0; i < tokens.size(); ++i)
      cout << tokens[i] << endl;

    return 0;
}

Output:

4
99
34
56
28
gsamaras
  • 71,951
  • 46
  • 188
  • 305