StringStream

  • + 5 comments

    Here's my solution:

    #include <iostream>
    #include <sstream>
    #include <vector>
    
    using namespace std;
    
    vector<int> parseInts(const string& str)
    {
        vector<int>  v;
        int          i;
        char         c;
        stringstream ss(str);
        while (ss >> i) { v.push_back(i);  ss >> c; }
        return v;
    }
    

    By the way, why don't we get well-written functions to work with? main could look like:

    int main()
    {
        string str;  cin >> str;
        for (const int& i : parseInts(str)) cout << i << endl;
        return 0;
    }
    

    instead of

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

    and notice the signature of parseInts avoiding copying the passed string when calling the function and helping the compiler in any optimization! But I've seen way worse in other exercices ...

    For the lulz:

    Although it doesn't respect all the requirements of the exercice (e.g. using parseInts), here's a 10-liner getting the job done:

    #include <iostream>
    #include <string>
    
    using namespace std;
    
    int main()
    {
        string s;  cin >> s;
        for (size_t f = 0; (f = s.find(",", f)) != string::npos; s.replace(f, 1, "\n"));
        cout << s << endl;
        return 0;
    }
    

    and, even better, a 6-liner only using the standard streams std::cin and std::cout (no strings)!

    #include <iostream>
    
    int main()
    {
        for (char c; std::cin >> c;) std::cout << (c != ','? c : '\n');
        return 0;
    }
    

    This will be hard to beat ...