Reputation: 5958
I am trying to extract integer sequences from a string in C++, which contains a certain delimiter, and create arrays with them:
The input is in the following format:
<integer>( <integer>)+(<delimiter> <integer>( <integer>)+)+
Example: 1 2 3 4; 5 6 7 8; 9 10
(Here the delimiter is ;
)
The result should be three integer arrays, containing:
[1, 2, 3, 4]
, [5, 6, 7, 8]
and [9, 10]
What I've tried so far is using istringstream
, because it already splits them by whitespace, but I didn't succeed:
#include <iostream>
#include <sstream>
using namespace std;
int main() {
string token;
cin >> token;
istringstream in(token);
// Here is the part that is confusing me
// Also, I don't know how the size of the newly created array
// will be determined
if (!in.fail()) {
cout << "Success!" << endl;
} else {
cout << "Failed: " << in.str() << endl;
}
return 0;
}
Upvotes: 0
Views: 49
Reputation: 1698
To carry off the previous answer is to read until the ';'
using std::getline
, then parse the string using std::istringstream
down to its spaces:
std::string tokens;
std::getline(cin, tokens);
std::istringstream token_stream(tokens);
std::vector<string> arr;
vector<vector<int>> toReturn
string cell;
while (getline(token_stream, cell, ';')
{
arr.push_back(cell);
}
for(int i = 0; i<arr.size(); i++)
{
istringstream n(arr[i]);
vector<int> temp;
while(getline(n, cell, ' ') temp.push_back(atof(cell));
toReturn.push_back(temp);
}
Upvotes: 1
Reputation: 57678
My suggestion is to read until the ';'
using std::getline
, then parse the string using std::istringstream
:
std::string tokens;
std::getline(cin, tokens, ';');
std::istringstream token_stream(tokens);
std::vector<int> numbers;
int value;
while (token_stream >> value)
{
numbers.push_back(value);
}
Upvotes: 1