0

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;
}

2 Answers 2

1

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);
}
Sign up to request clarification or add additional context in comments.

Comments

1

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);
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.