getline 与 istream_iterator

发布于 2024-08-11 22:46:13 字数 74 浏览 3 评论 0原文

如果您要从文件中逐行输入(将行读入字符串,以进行标记化),是否应该有理由选择 getline 或 istream_iterator 。

Should there be a reason to preffer either getline or istream_iterator if you are doing line by line input from a file(reading the line into a string, for tokenization).

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

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

发布评论

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

评论(3

匿名。 2024-08-18 22:46:13

我有时(根据情况)编写一个行类,这样我就可以使用 istream_iterator :

#include <string>
#include <vector>
#include <iterator>
#include <iostream>
#include <algorithm>

struct Line
{
    std::string lineData;

    operator std::string() const
    {
        return lineData;
    }
};
std::istream& operator>>(std::istream& str,Line& data)
{
    std::getline(str,data.lineData);
    return str;
}

int main()
{
     std::vector<std::string>    lines(std::istream_iterator<Line>(std::cin),
                                       std::istream_iterator<Line>());
}

I sometimes (depending on the situation) write a line class so I can use istream_iterator:

#include <string>
#include <vector>
#include <iterator>
#include <iostream>
#include <algorithm>

struct Line
{
    std::string lineData;

    operator std::string() const
    {
        return lineData;
    }
};
std::istream& operator>>(std::istream& str,Line& data)
{
    std::getline(str,data.lineData);
    return str;
}

int main()
{
     std::vector<std::string>    lines(std::istream_iterator<Line>(std::cin),
                                       std::istream_iterator<Line>());
}
揽清风入怀 2024-08-18 22:46:13

getline 将为您提供整行,而 istream_iterator 将为您提供单个单词(以空格分隔)。

取决于您想要完成的任务,如果您问哪个更好(标记化只是一位,例如,如果您期望一个结构良好的程序并且希望解释它,那么整行阅读可能会更好。 .)

getline will get you the entire line, whereas istream_iterator<std::string> will give you individual words (separated by whitespace).

Depends on what you are trying to accomplish, if you are asking which is better (tokenization is just one bit, e.g. if you are expecting a well formed program and you expect to interpret it, it may be better to read in entire lines...)

四叶草在未来唯美盛开 2024-08-18 22:46:13

@Martin York 的答案虽然有效,但在与 STL 算法一起使用时在许多方面都失败了。一个更简单的解决方案是使用继承。

struct line : public std::string{
    using std::string::string;
};

std::istream& operator>>(std::istream& s, line& l){
    std::getline(s, l);
    return s;
}

@Martin York's answer-- while works-- fails in many areas when used with STL's algorithm. A simpler solution is to use inheritance.

struct line : public std::string{
    using std::string::string;
};

std::istream& operator>>(std::istream& s, line& l){
    std::getline(s, l);
    return s;
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文