从标准输入读取数组,忽略括号和逗号 [英] Read an array from standard input, ignoring brackets and commas
本文介绍了从标准输入读取数组,忽略括号和逗号的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我的代码的示例输入为:
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.
我该怎么做?
推荐答案
使用正则表达式
一个简单的解决方法是使用C ++ 11 正则表达式来简单地将所有不需要的字符替换为空格,然后像往常一样使用流对整数进行标记。
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.
假设您已将输入读入名为 s
的字符串中,例如
Let's say you've read the input into a string called s
, e.g.
std::getline(std::cin, s);
然后,您可以简单地将所有整数读入 std :: vector
使用这两行:
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>{}};
这篇关于从标准输入读取数组,忽略括号和逗号的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文