Read an array from standard input, ignoring brackets and commas

前端 未结 4 618
广开言路
广开言路 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: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 v{std::istream_iterator{ss}, std::istream_iterator{}};
    

    Live Example

提交回复
热议问题