Search code examples
c++istream-iterator

how to use istream_iterators to split an equation?


I'm trying to split a string like ( 1 + 2 ) into a vector and when using an istream_iterators<string> it doesn't split the parentheses so I get vector outputs like

(1 , + , 2) when I want ( , 1, + , 2 ,)

Is it possible to use istream_iterators to achieve this?

string eq = "(1 + 2)";

istringstream ss(eq);
istream_iterator<string> begin(ss);
istream_iterator<string> end;
vector<string> vec(begin, end);

Solution

  • I don't think you can do it using istream_iterator. Instead, simply do it by hand:

    vector<string> vec;
    vec.reserve(eq.size() / 4); // rough guess
    bool in_number = false;
    for (char ch : eq) {
        if (isspace(ch)) {
            in_number = false;
        } else if (isdigit(ch)) {
            if (in_number) {
                vec.back().push_back(ch);
            } else {
                vec.emplace_back(1, ch);
                in_number = true;
            }
        } else {
            vec.emplace_back(1, ch);
            in_number = false;
        }
    }