Insert line before text in cpp

My problem is that I want to add some line before iostream. You can say before std :: cin.

#include <iostream>
#include <string>

void print(std::istream & in){// function not to be modified
    std::string str;
    in >> str;
    std::cout<< str << std::endl;
    in >> str;
    std::cout<< str << std::endl;
}

int main() {
    std::string header = "hello ";
    //boost::iostream::filtering_istream in(std::cin);
    std::istream & in = std::cin;

    //you may do someting here
    //something like inserting characters into cin or something with buffers

    print(in);
}

I want the fuction implementation to be such that if I provide input like

$ cat file.txt
help me to solve this.
$
$ ./a.out < file
hello
help
$

any help is appreciated. you can use boost :: iostream to implement it.

+3
source share
2 answers

A stream is not a container. This is a data stream. You cannot change data that has already passed. The only exceptions are streams tied to block devices in which you can search, for example. fstream- but even then you can only overwrite.

, header , .

+3

. , .

Low-Tech

"" - , "" :

Live On Coliru

#include <iostream>
#include <string>
#include <sstream>

void print(std::istream &in) { // function not to be modified
    std::string str;
    while (in >> str)
        std::cout << str << std::endl;
}

int main() {
    std::string header = "hello ";
    std::stringstream in;
    in << header << std::cin.rdbuf();

    print(in);
}

foo bar qux :

hello
foo
bar
qux

High-Tech

, :

Live On Coliru

#include <iostream>
#include <sstream>
#include <vector>

template <typename B1, typename B2>
class cat_streambuf : public std::streambuf {
    B1* _sb1;
    B2* _sb2;
    std::vector<char> _buf;
    bool _insb1 = true;

  public:
    cat_streambuf(B1* sb1, B2* sb2) : _sb1(sb1), _sb2(sb2), _buf(1024) {}

    int underflow() {
        if (gptr() == egptr()) {
            auto size = [this] {
                if (_insb1) {
                    if (auto size = _sb1->sgetn(_buf.data(), _buf.size()))
                        return size;
                    _insb1 = false;
                }

                return _sb2->sgetn(_buf.data(), _buf.size());
            }();

            setg(_buf.data(), _buf.data(), _buf.data() + size);
        }
        return gptr() == egptr() 
            ? std::char_traits<char>::eof()
            : std::char_traits<char>::to_int_type(*gptr());
    }
};

void print(std::istream &in) { // function not to be modified
    std::string str;
    while (in >> str)
        std::cout << str << std::endl;
}

int main() {
    std::stringbuf header("hello ");
    cat_streambuf both(&header, std::cin.rdbuf());

    std::istream is(&both);
    print(is);
}

hello
foo
bar
qux

. , , () .

0

All Articles