Home > OS >  parsing input in c for competitive programming
parsing input in c for competitive programming

Time:10-20

How to parse input like for example:

[[1,3,5,7],[10,11,16,20],[23,30,34,60]]

for 2d vector of m x n size. I have tried

char x;
vector<int> v;
vector<vector<int>> v_v;

vector<int> temp;

int br_op_cl = 0;
int row = 0;

while (cin >> x) {
    // cout << x << endl;
    if (x == '[' || x == '{') {
        // cout << "inside [" << endl;
        br_op_cl  ;
        cout << "inside [ " << br_op_cl << endl;
    } else if (x == ']' || x == '}') {
        cout << "inside ] " << x << endl;
        br_op_cl--;
    } else if (x >= 0 && x != ',') {
        cout << "inside 0-9 " << x << endl;
        temp.push_back(x);
        if (br_op_cl % 2 != 0) {
            cout << br_op_cl << " inside br_op_cl " << '\n';
            v_v.push_back(temp);
        }
    }
}

and the output is

49 51 53 55 49 48 49 49 49 54 50 48 50 51 51 48 51 52 54 48 

which is ascii values of the each digit. Any help for how to read chars and int together and parsing techniques in c

CodePudding user response:

Consider [1,3,5,7] to be a single row. Use stringstream to read this row. Then use another stringstream to read the content of this row.

getline will read each row until it hits ], another getline will read each column until it hits ].

Replace occurrences of { with [, to make parsing easier.

#include <iostream>
#include <vector>
#include <string>
#include <sstream>
#include <algorithm>

int main()
{
    std::string str = "[[1,3,5,7],[10,11,16,20],[23,30,34,60]]";
    replace(str.begin(), str.end(), '{', '[');
    replace(str.begin(), str.end(), '}', ']');
    std::stringstream ss(str);
    std::vector<std::vector<int>> res;
    if (ss.get() != '[')
        return 0;
    char c;
    while (ss >> c && c != ']') {
        if (c == '[') {
            getline(ss, str, ']');
            std::stringstream scol(str);
            std::vector<int> vec;
            while (getline(scol, str, ','))
                vec.push_back(std::stoi(str));
            res.push_back(vec);
        }
    }
    for (auto& row : res) {
        for (auto& col : row) std::cout << col << ",";
        std::cout << "\n";
    }
    return 0;
}
  • Related