[英]Overloading operator>> to create array from string
I would like to create an std::array
from a std::string
.我想从
std::string
创建一个std::array
。
For this, I would like to overload the operator>>
.为此,我想重载
operator>>
。
I have the following test case:我有以下测试用例:
std::istream& operator>>(std::istream& is, const std::array<double, 3>& a)
{
char p1, p2;
is >> p1;
// if fail warn the user
for (unsigned int i = 1; i < a.size(); ++i)
{
// something to ignore/ check if numeric
}
is >> p2;
// if fail warn the user
return is;
}
int main()
{
std::string a = "[1 2 3]";
std::array<double, 3> arr;
std::istringstream iss (a);
iss >> arr;
return 0;
}
I would like for the operator to check if the characters [
and ]
are in the correct place and to construct the array with the elements inside.我想让操作员检查字符
[
和]
是否在正确的位置,并用里面的元素构造数组。
How can I do checks if the extraction was successfull?如何检查提取是否成功? How can I check the string between the parenthesis is numeric and if so construct my array from it?
如何检查括号之间的字符串是否为数字,如果是,如何从中构造我的数组?
Kind regards亲切的问候
I'd add a helper class that checks for a certain character in the stream and removes it if it's there.我会添加一个助手 class 来检查 stream 中的某个字符,如果存在则将其删除。 If it's not, sets the failbit.
如果不是,则设置故障位。
Example:例子:
#include <cctype>
#include <istream>
template <char Ch, bool SkipWhitespace = false>
struct eater {
friend std::istream& operator>>(std::istream& is, eater) {
if /*constexpr*/ (SkipWhitespace) { // constexpr since C++17
is >> std::ws;
}
if (is.peek() == Ch) // if the expected char is there, remove it
is.ignore();
else // else set the failbit
is.setstate(std::ios::failbit);
return is;
}
};
And it could then be used like this:然后它可以像这样使用:
std::istream& operator>>(std::istream& is, std::array<double, 3>& a) {
// use the `eater` class template with `[` and `]` as template parameters:
return is >> eater<'['>{} >> a[0] >> a[1] >> a[2] >> eater<']'>{};
}
int main() {
std::string a = "[1 2 3]";
std::array<double, 3> arr;
std::istringstream iss (a);
// iss.exceptions(std::ios::failbit); // if you want exceptions on failure
if(iss >> arr) {
std::cout << "success\n";
} else {
std::cout << "fail\n";
}
}
Demo where ,
is used as separator in the input.演示,其中
,
在输入中用作分隔符。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.