1

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.

How can I do that?

Felix Glas
  • 15,065
  • 7
  • 53
  • 82
roynalnaruto
  • 329
  • 2
  • 6
  • 17
  • 3
    Perhaps by searching the web for examples of "c++ read comma separated values". – Thomas Matthews Nov 03 '14 at 23:21
  • 1
    I'd start from [a previous answer](http://stackoverflow.com/a/1895584/179910) and add a couple of lines to the `csv_reader` facet to get it to treat `{` and `}` as white-space (just like it currently does for comma, space and new-line. – Jerry Coffin Nov 03 '14 at 23:28

4 Answers4

2

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.

Thomas Matthews
  • 56,849
  • 17
  • 98
  • 154
2

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

Felix Glas
  • 15,065
  • 7
  • 53
  • 82
1

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;
}
mattnewport
  • 13,728
  • 2
  • 35
  • 39
0

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>());
Ziezi
  • 6,375
  • 3
  • 39
  • 49