C++迭代 istream

发布于 2024-09-29 04:07:00 字数 121 浏览 1 评论 0原文

解析或迭代 istream 的最佳方法是什么?我需要创建一个接受 istream 的函数,解析它并创建一个对象,所以想知道最简单的方法来做到这一点。即使是可以将其转换为 string 的东西也会很花哨。

What is the best way to parse or iterate an istream? I need to create a function that takes an istream, parses it and creates an object so was wondering the easiest way to do this. Even something that could convert it to string would be dandy.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

歌入人心 2024-10-06 04:07:01

您可以使用 istream_iterator

typedef std::istream_iterator<std::string> streamiter;
for (streamiter it = streamiter(some_istream); it != streamiter(); it++) {
    // process words
}

这将在所有空白处分割输入流。

You can use an istream_iterator.

typedef std::istream_iterator<std::string> streamiter;
for (streamiter it = streamiter(some_istream); it != streamiter(); it++) {
    // process words
}

This will split the input stream at all whitespaces.

熊抱啵儿 2024-10-06 04:07:01

由于 C++ 没有内置反射和持久性,因此您无法编写读取任何对象的函数,然后查看它会产生什么结果。您需要事先知道您要寻找什么并具体阅读。 (当然,您始终可以只读取标记并将其输入解析器。)

如果您确切地知道要从流中读取哪种类型的对象,通常最好为该类提供一个采用 std::istream& 的构造函数。 。由于通常类也是写入流的代码所在的位置,因此这将它们放在一起,这最有利于维护。然后,解析代码仅创建将流传递给构造函数的对象。

如果您不知道会遇到哪种类型,则必须编写一个(可能很简单)解析函数。此类格式应以一个标识符开头,该标识符表明后面跟随的是哪种类型的对象。您的解析函数首先必须读取该标识符,然后分支到从流中读取适当类型的代码。由于此时它知道要从流中读取什么类型的对象,因此可以在构造函数中实现读取实际对象,如上所述。

Since C++ doesn't have reflection and persistence built in, you cannot write a function that reads any object and then see what it came up with. You need to know what you are looking for before-hand and read that specifically. (Of course you could always just read tokens and feed those into a parser.)

If you know exactly which type of object to read from the stream, it's often good to give that class a constructor taking a std::istream&. Since usually the class is also where the code to write into the stream is, this puts both of them close together, which is best for maintenance. The parsing code then just creates the object passing the stream to the constructor.

If you don't know which type you will encounter, you will have to write a (probably simple) parsing function. Such formats should start with an identifier that tells which type of objects follow. Your parsing function would first have to read that identifier, and then branch into code that reads the appropriate type from the stream. Since at this point it knows what type of object to read from the stream, reading the actual objects can be implemented in constructors as described above.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文