如何使std :: istream_iterator只读到行尾?

时间:2019-06-01 15:31:14

标签: c++ istream istream-iterator

具有以下代码:

std::vector<int64> values;
std::copy(
  std::istream_iterator<int64>(std::cin),
  std::istream_iterator<int64>(),
  std::back_inserter(values)
);

我想让它只读取输入流,直到行尾。我该如何使用std::istream_iterator来做到这一点?

4 个答案:

答案 0 :(得分:3)

如果您想要功能而不添加std::getlinestd::stringstream,则可以更改流的字符分类,以使换行符不被视为可丢弃的空格。这是一个最小的示例:

struct set_newline_as_ws : std::ctype<char> {
  static const mask* make_table( std::ctype_base::mask m ) {
    static std::vector<mask> v(classic_table(), classic_table() + table_size);
    v['\n'] &= m;
    return &v[0];
  }
  set_newline_as_ws( bool skip, std::size_t refs = 0 ) : ctype(make_table(skip ? ~space : space), false, refs) {}
};

std::istream& skipnewline( std::istream& is ) {
  is.imbue(std::locale(is.getloc(), new std::ctype<char>));
  return is;
}

std::istream& noskipnewline( std::istream& is ) {
  is.imbue(std::locale(is.getloc(), new set_newline_as_ws(true)));
  return is;
}

int main() {
  std::vector<int64> values;
  std::cin >> noskipnewline;
  std::copy(
    std::istream_iterator<int64>(std::cin),
    std::istream_iterator<int64>(),
    std::back_inserter(values)
  );
  std::cin >> skipnewline;
}

答案 1 :(得分:3)

您无法使用std::istream_iterator

但是编写输入迭代器相对容易。

#include <iterator>
#include <iostream>
#include <sstream>
#include <vector>
#include <cctype>

template<typename T>
class istream_line_iterator: public std::iterator<std::input_iterator_tag, T>
{
    std::istream*   stream;
    public:
        // Creating from a stream or the end iterator.
        istream_line_iterator(std::istream& s): stream(&s)      {dropLeadingSpace();}
        istream_line_iterator():                stream(nullptr) {}

        // Copy
        istream_line_iterator(istream_line_iterator const& copy): stream(copy.stream)   {}
        istream_line_iterator& operator=(istream_line_iterator const& copy) {stream = copy.stream;return *this;}

        // The only valid comparison is against the end() iterator.
        // All other iterator comparisons return false.
        bool operator==(istream_line_iterator const& rhs) const {return stream == nullptr && rhs.stream == nullptr;}
        bool operator!=(istream_line_iterator const& rhs) const {return !(*this == rhs);}

        // Geting the value modifies the stream and returns the value.
        // Note: Reading from the end() iterator is undefined behavior.
        T  operator*() const    {T value;(*stream) >> value;return value;}
        T* operator->() const;  // Not sure I want to implement this.

        // Input streams are funny.
        // Does not matter if you do a pre or post increment. The underlying stream has changed.
        // So the effect is the same.
        istream_line_iterator& operator++()     {dropLeadingSpace();return *this;}
        istream_line_iterator& operator++(int)  {dropLeadingSpace();return *this;}

    private:
        void dropLeadingSpace()
        {
            // Only called from constructor and ++ operator.
            // Note calling this on end iterator is undefined behavior.

            char c;
            while((*stream) >> std::noskipws >> c) {
                if (c == '\n') {
                    // End of line. So mark the iterator as reaching end.
                    stream = nullptr;
                    return;
                }
                if (!std::isspace(c)) {
                    // Found a non space character so put it back
                    stream->putback(c);
                    return;
                }
            }
            // End of stream. Mark the iterator as reaching the end.
            stream = nullptr;
        }
};

int main()
{
    std::stringstream    s{"0 1 2 3 4 5 6 7 8 9 10\n11 12 13 14 15 16\n17 18 19"};

    std::vector<int>    d{istream_line_iterator<int>(s), istream_line_iterator<int>()};
    for(auto v: d) {
        std::cout << "V: " << v << "\n";
    }
}

运行:

> g++ -std=c++17 main.cpp
> ./a.out
V: 0
V: 1
V: 2
V: 3
V: 4
V: 5
V: 6
V: 7
V: 8
V: 9
V: 10

答案 2 :(得分:2)

从先前的答案到类似的问题(here):

namespace detail 
{
    class Line : std::string 
    { 
        friend std::istream & operator>>(std::istream & is, Line & line)
        {   
            return std::getline(is, line);
        }
    };
}

template<class OutIt> 
void read_lines(std::istream& is, OutIt dest)
{
    typedef std::istream_iterator<detail::Line> InIt;
    std::copy(InIt(is), InIt(), dest);
}

int main()
{
    std::vector<std::string> v;
    read_lines(std::cin, std::back_inserter(v));

    return 0;
}

答案 3 :(得分:0)

istream_iterator将读取流,直到找到EOF。您可以简单地调整流以在找到换行符后返回EOF。可以通过临时更改其rdbuf来完成:

#include <algorithm>
#include <iostream>
#include <iterator>
#include <sstream>
#include <streambuf>
#include <vector>

class newline_buf : public std::streambuf {
    std::streambuf* src;
    char ch; // single-byte buffer
protected:
    int underflow() {
        if( (ch= src->sbumpc()) == '\n') {
            return traits_type::eof(); // return EOF on new line.
        }
        setg(&ch, &ch, &ch+1); // make one read position available
        return ch; // may also return EOF by the regular means
    }
public:
    newline_buf(std::streambuf* buf) : src(buf) {
        setg(&ch, &ch+1, &ch+1); // buffer is initially full
    }
};

int main() {
    // testing with a stringstream to make things easier to reproduce.
    // Should work fine with any type of input stream.
    std::istringstream iss(R"(12345 12345 12345 
    67890 67890 67890)");

    // We store the original rdbuf so we can recover it later.
    auto original_rdbuf = iss.rdbuf();
    newline_buf buf(original_rdbuf);
    iss.basic_ios::rdbuf(&buf);

    // Do the copy and then recover the original rdbuf
    std::copy(std::istream_iterator<int>(iss), std::istream_iterator<int>(), std::ostream_iterator<int>(std::cout, " "));
    iss.basic_ios::rdbuf(original_rdbuf);

    // You can try doing a new copy, just to convince yourself that the stream is still in a valid state.
    //std::copy(std::istream_iterator<int>(iss), std::istream_iterator<int>(), std::ostream_iterator<int>(std::cout, " "));
}

See it live!