重载 C++ 的示例提取运算符>>解析数据
我正在寻找一个很好的示例,说明如何重载流输入运算符(运算符>>)以使用简单的文本格式解析一些数据。我已阅读本教程,但我想做一些更高级的事情。就我而言,我有固定的字符串,我想检查(并忽略)。假设链接中的 2D 点格式更像
Point{0.3 =>
0.4 }
是解析出数字 0.3 和 0.4 的预期效果。 (是的,这是一个非常愚蠢的语法,但它包含了我需要的几个想法)。大多数情况下,我只是想看看如何正确检查固定字符串是否存在,忽略空格等。
更新: 哎呀,我在下面发表的评论没有格式(这是我第一次使用这个网站)。 我发现可以用类似
std::cin >> std::ws;
And 之类的方法跳过空格,因为
static bool match_string(std::istream &is, const char *str){
size_t nstr = strlen(str);
while(nstr){
if(is.peek() == *str){
is.ignore(1);
++str;
--nstr;
}else{
is.setstate(is.rdstate() | std::ios_base::failbit);
return false;
}
}
return true;
}
现在如果能够获取解析错误的位置(行号),那就太好了。
更新2: 仅使用 1 个字符前瞻即可实现行号和注释解析。最终结果可以在 AArray.cpp 中的 parse() 函数中看到。该项目是一个可(反)序列化的 C++ PHP 类数组类。
I am looking for a good example of how to overload the stream input operator (operator>>) to parse some data with simple text formatting. I have read this tutorial but I would like to do something a bit more advanced. In my case I have fixed strings that I would like to check for (and ignore). Supposing the 2D point format from the link were more like
Point{0.3 =>
0.4 }
where the intended effect is to parse out the numbers 0.3 and 0.4. (Yes, this is an awfully silly syntax, but it incorporates several ideas I need). Mostly I just want to see how to properly check for the presence of fixed strings, ignore whitespace, etc.
Update:
Oops, the comment I made below has no formatting (this is my first time using this site).
I found that whitespace can be skipped with something like
std::cin >> std::ws;
And for eating up strings I have
static bool match_string(std::istream &is, const char *str){
size_t nstr = strlen(str);
while(nstr){
if(is.peek() == *str){
is.ignore(1);
++str;
--nstr;
}else{
is.setstate(is.rdstate() | std::ios_base::failbit);
return false;
}
}
return true;
}
Now it would be nice to be able to get the position (line number) of a parsing error.
Update 2:
Got line numbers and comment parsing working, using just 1 character look-ahead. The final result can be seen here in AArray.cpp, in the function parse(). The project is a (de)serializable C++ PHP-like array class.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您的运算符>>(istream &, object &) 应该使用其格式化和/或未格式化的提取函数从输入流获取数据,并将其放入您的对象中。
如果您想更安全(以某种方式),请在开始之前构建并测试 istream::sentry 对象。如果遇到语法错误,可以调用
setstate( ios_base::failbit )
来阻止任何其他处理,直到调用 my_stream.clear()。请参阅
(如果您使用的是 SGI STL,请参阅 istream.tcc)作为示例。Your operator>>(istream &, object &) should get data from the input stream, using its formatted and/or unformatted extraction functions, and put it into your object.
If you want to be more safe (after a fashion), construct and test an istream::sentry object before you start. If you encounter a syntax error, you may call
setstate( ios_base::failbit )
to prevent any other processing until you call my_stream.clear().See
<istream>
(and istream.tcc if you're using SGI STL) for examples.