Lasse Skyum wrote in
Hi Mike,
I'm sure that would be a verry clever way to do it... unfortunatly I
don't understand what you mean by "custom extractor" ... is that a C++
STL thing? (I'm verry new to STL)
Not really, STL isn't an offical term, when used sensibly is means
the standard containers, iterators and algorithms libraries, e.g.
std::vector< T >, std::set< T >, and std::sort().
Here is a class Test with its own extractor an inserter.
#include <iostream>
#include <ostream>
#include <iomanip>
#include <sstream>
class Test
{
int a, b;
public:
Test() {}
Test( int aa, int bb ) : a( aa ), b ( bb ) {}
friend std::istream &operator >> (
std::istream &is,
Test &rhs
);
friend std:
stream &operator << (
std:
stream &os,
Test const &rhs
)
{
return os << "(" << rhs.a << "," << rhs.b << ")";
}
};
std::istream &operator >> (
std::istream &is,
Test &rhs
)
{
char c;
if ( !(is >> c) ) return is;
if ( c != '(' )
{
is.setstate( std::ios_base::failbit );
return is;
}
if ( !(is >> rhs.a) ) return is;
if ( !(is >> c ) ) return is;
if ( c != ',' )
{
is.setstate( std::ios_base::failbit );
return is;
}
if ( !(is >> rhs.b) ) return is;
if ( !(is >> c ) ) return is;
if ( c != ')' )
{
is.setstate( std::ios_base::failbit );
return is;
}
return is;
}
int main()
{
using namespace std;
Test a( 1, 2), b( 3, 4 ), c;
stringstream ss;
ss << a << " " << b << " %";
if (ss >> c) cerr << "extracted c\n";
else cerr << "didn't extract c\n";
cerr << a << ", " << b << ", " << c << "\n";
if (ss >> c) cerr << "extracted c\n";
else cerr << "didn't extract c\n";
cerr << a << ", " << b << ", " << c << "\n";
if (ss >> c) cerr << "extracted c\n";
else cerr << "didn't extract c\n";
if ( ss.fail() ) cerr << "ss failbit set\n";
else cerr << "ss failbit clear\n";
}
My plan is now just to make my own CIStream, COStream, CIOStream with
similar functionality so I can easily switch over. Just thought I
would stick to standard C++ to make it more "clean" and reusable...
Providing your own stream inserters (operator <<) and extractors
(operator >>) is "clean" and reusable..
Rob.