Re: question about streams
It's quite simple. In my example, the "parse" function simply prints the input, but it could do whatever. It works with a file, with the console or a stringstream:
Code:
#include <iostream>
#include <fstream>
#include <sstream>
using namespace std;
template <typename E, typename T>
void parse(basic_istream<E, T> &s)
{
E e;
while(s.read(&e, 1)) cout<<e;
}
int main()
{
ifstream f("c:\\boot.ini");
parse(f);
parse(cin);
stringstream ss;
ss << "abc";
parse(ss);
return 0;
}
Re: question about streams
Is there a way to do this without templates? :)
Can you show sample code without templates?
Thanks
Re: question about streams
What's wrong with templates? The standard library is full of them and they are one of the major strengthes of C++. And my example won't involve a more extensive use of templates than it does when used in real life (that is with parse() implemented).
To answer your question: yes, you can do it without templates. Pseudocode:
Code:
if(your_int == 0)
{
FILE *f = fopen("filename");
fread(f, buffer, size_of_file);
parse(buffer); // buffer is of course a byte buffer
} else {
put_string_in_buffer(s, buffer);
parse(buffer);
}
Basically parse() always parses a buffer. All you need to do is to take out the functionality of filling that buffer. ;)
Re: question about streams
I don't have any documentation in front of me right now,
but isn't std::istream a common base class ?
Code:
#include <string>
#include <sstream>
#include <iostream>
#include <fstream>
using namespace std;
void Parse(std::istream & in)
{
string str;
getline(in,str);
std::cout << str << "\n";
}
int main()
{
ifstream in("somefile");
Parse(in);
istringstream ss("this is a test");
Parse(ss);
return 0;
}