Read an array from standard input, ignoring brackets and commas

前端 未结 4 616
广开言路
广开言路 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 <algorithm>
    #include <cctype>
    #include <iostream>
    #include <iterator>
    #include <string>
    
    using namespace std;
    
    int main() {
        vector<int> nums;
        for_each(istream_iterator<string>{cin}, istream_iterator<string>{}, [&](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<int>{cout, ", "});
        cout << endl;
    }
    
    0 讨论(0)
  • 2021-01-16 12:26

    Read an array from standard input, ignoring brackets and commas into a vector.

    #include <algorithm>    // std::replace_if()
    #include <iterator>     // std::istream_iterator<>()
    #include <sstream>      // std::stringstream
    #include <vector>       // std::vector
    
    std::getline(std::cin, line); // { 1, 2, 3, 4 }
    
    std::replace_if(line.begin(), line.end(),
                    [](const char& c) { return ((c == '{') || (c == ',') || (c == '}')); },
                    ' ');
    
    std::stringstream ss(line); // 1 2 3 4
    
    std::vector<int> v((std::istream_iterator<int>(ss)),
                        std::istream_iterator<int>());
    
    0 讨论(0)
  • 2021-01-16 12:28

    Using Regex

    An easy fix is to use C++11 regular expressions to simply replace all unwanted characters with whitespace and then tokenize the integers using streams as usual.

    Let's say you've read the input into a string called s, e.g.

    std::getline(std::cin, s);
    

    Then you can simply read all the integers into a std::vector using these two lines:

    std::istringstream ss{std::regex_replace(s, std::regex{R"(\{|\}|,)"}, " ")};
    std::vector<int> v{std::istream_iterator<int>{ss}, std::istream_iterator<int>{}};
    

    Live Example

    0 讨论(0)
  • 2021-01-16 12:49

    Hmmm, this might work:

    // Ignore all characters up to and including the open curly bracket
    cin.ignore(100000, '{');
    
    // Read the numbers into an array
    int my_array[4];
    unsigned int array_index = 0;
    cin >> my_array[array_index];
    array_index++;
    cin >> my_array[array_index];
    array_index++;
    cin >> my_array[array_index];
    array_index++;
    cin >> my_array[array_index];
    
    // Ignore all characters up to and including the newline.
    cin.ignore(1000000, '\n');
    

    You could use a for loop to read in the numbers.

    0 讨论(0)
提交回复
热议问题