StringStream

  • + 1 comment

    So, I wrote this code and this works too, though I still have a doubt: in the for loop where I do v.push_back(a), how does the code know where to begin parsing stringstream ss. I mean it could just keep on parsing the first integer and the first character.

    Can somebody please explain this?

    #include <sstream>
    #include <vector>
    #include <iostream>
    using namespace std;
    
    vector<int> parseInts(string str) {
        int n = 0;
        for (int i=0; i<str.size(); ++i) {
            if (str[i]==',') ++n;
        }
        
        vector<int> v;
        stringstream ss(str);
        
        for (int i=0; i<=n; ++i) {
            char ch;
            int a;
            ss >> a >> ch;
            v.push_back(a);
        }
        
        return v;
    }
    
    int main() {
        string str;
        cin >> str;
        vector<int> integers = parseInts(str);
        for(int i = 0; i < integers.size(); i++) {
            cout << integers[i] << "\n";
        }
        
        return 0;
    }
    
    • + 2 comments

      by vector v the element is inserted that is pushback of a.