Read an array from standard input, ignoring brackets and commas

前端 未结 4 619
广开言路
广开言路 2021-01-16 12:05

The sample input to my code is:

{ 1, 2, 3, 4 }

I wish to ignore the curly brackets and commas, and read the numbers into an array.

4条回答
  •  野的像风
    2021-01-16 12:23

    Here's a way to do it:

    #include 
    #include 
    #include 
    #include 
    #include 
    
    using namespace std;
    
    int main() {
        vector nums;
        for_each(istream_iterator{cin}, istream_iterator{}, [&](string s) {
            s.erase(remove_if(begin(s), end(s), [](char c) { return !isdigit(c); }), end(s));
            if (!s.empty())
                nums.push_back(stoi(s));
        });
        copy(begin(nums), end(nums), ostream_iterator{cout, ", "});
        cout << endl;
    }
    

提交回复
热议问题