Read an array from standard input, ignoring brackets and commas

↘锁芯ラ 提交于 2019-12-01 10:23:42

问题


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?


回答1:


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.




回答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




回答3:


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



回答4:


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>());


来源:https://stackoverflow.com/questions/26725035/read-an-array-from-standard-input-ignoring-brackets-and-commas

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!