My problem is something like I want to append some string in front of a iostream. You can say in front of 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 implementation of the fuction such that if I provide input like
$ cat file.txt
help me to solve this.
$
$ ./a.out < file
hello
help
$
any kind of help is welcome. you may use boost::iostream to implement it.
A stream is not a container. It is a flow of data. You cannot change data that has already floated away. The only exception is streams tied to block devices, in which you can seek around, e.g.
fstream
- but even then you can only overwrite.Instead, structure your code so that
header
is consumed before the stream is consulted at all.You should avoid the issue. Just don't parse it all from the same stream if it isn't the same stream.
Low-Tech
A low-tech "solution" is to copy the stream to a stringstream, putting your "prefix" in the buffer first:
Live On Coliru
Given the input
foo bar qux
prints:High-Tech
You can always create a custom stream buffer that implements the behaviour you desire:
Live On Coliru
Which also prints
for the same input. This will definitely scale better for (very) large streams.