Cubbi, You guessed my intent correctly and the example explains it right. However, it is difficult to implement it.
I couldn't completely understand this:
you'd need to write a buffer (not a stream) class and implement an underflow() which would write to the file. Your myistream will just have the constructor to forward the file name to the buffer's constructor (which is what ifstream does) |
What does writing a buffer mean?
What is underflow()?
Another failed (but not completely failed) attempt:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37
|
class pipe
{
std::istream* isp; //input stream pointer
std::ostream* osp; //output stream pointer
std::istringstream str_stream;
std::string str;
public:
pipe(std::istream* input,std::ostream* output):isp(input),osp(output){}
template<class typ>
pipe& operator>>(typ& obj)
{
(*isp)>>str;
(*osp)<<str<<'\n';
str_stream.clear();
str_stream.str(str);
str_stream>>obj;
return *this;
}
};
int main()
{
ofstream ofile("tile.txt");
pipe mycin(&std::cin,&ofile);
string str;
int x;
cout<<"Enter a number ";
mycin>>x;
cout<<x<<endl;
cout<<"Enter a string ";
mycin>>str;
cout<<str<<endl;
}
|
This attempt works fine but now I'll have to write functions like gcount(), good(),eof(),etc. I don't want to do this. I want to write only those functions which have changed functionality. Hence, I have to inherit from std::istream.
But this poses a problem. std::istream doesn't have a default constructor. It only has this constructor:
explicit basic_istream (basic_streambuf<char_type,traits_type>* sb);
Hence, I must call istream's constructor from within myistream's constructor. Before writing code to output things to a file, I wanted to make sure that no compile errors occur in this constructor thing.
So I made a simple constructor for myistream to just pass its parameter to istream's constructor. Also I didn't write func()'s actual implementation. I haven't written much code yet. I've just written the bare minimum to test this constructor issue. When this issue gets resolved, I will write myistream(const char*) so that Cubbi's example works.