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.
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.
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