-
November 22nd, 2005, 12:09 PM
#1
question about streams
Hello,
I have a function that I would like to either send it a ifstream or a string (maybe a string stream)?
So say I have this code:
string test = "hello this is a string to be parsed";
if(testint == 0)
{
ifstream in(fileName);
}
else
{
// put string in a stream here?
}
ParseData(generic stream?);
Can someone help me fill in the missing pieces to this code? basically I need to parse either a file or a string and I was hoping to use the same code to do either with maybe a generic stream?
Thanks!
-
November 22nd, 2005, 12:51 PM
#2
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;
}
-
November 22nd, 2005, 01:54 PM
#3
Re: question about streams
Is there a way to do this without templates?
Can you show sample code without templates?
Thanks
-
November 22nd, 2005, 02:42 PM
#4
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.
-
November 22nd, 2005, 04:35 PM
#5
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;
}
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|