Then I recommend you overload the getline() function, not the extraction operator. IMO making your overloads different just to make them different will cause confusion for everyone but yourself. And you'll probably be confused after a while as well.
There is a problem to solve in allocating enough space for an unknown # of characters coming in the stream. I solved this by declaring a local char array char buff[buffSz]; for use as an input buffer, then repeatedly allocate larger blocks to mainString as buff is filled over and over from the stream. I found the std::istream::get( char*, streamsize n, char delim ) useful.
See: http://www.cplusplus.com/reference/istream/istream/get/
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
std::istream& operator>>( std::istream& is, myStr& s )
{
constint buffSz = 6;// low for easy testing
char buff[buffSz];
s.sz = 0;
int n = 0;// # chars extracted each get
while( is.get( buff, buffSz, '\n' ) )// call will fail if '\n' is next. ie. it won't return just '\0'
{
// find n
// new array size = exist + n + 1
// the usual allocate/ copy/ delete steps
}
return is;
}
Or, have you found a way to avoid having to read in chunks like this?
Yes it was. The default operator is inappropriate in this case. We must write one ourselves.
I hope you've also written a copy constructor. The default version of that won't do either.
Are you asking what if we knew how many chars are coming in the stream before we read so we can allocate the exact right amount of space right up front?
That would be great, but I don't know of any way to obtain that number. I think we're stuck with reading from the stream until it's empty. Then we know how many chars there were!
IN could be an ifstream (reading from a file) and there may be millions of chars coming!
You need to consider more than 100 chars may be in the stream, so buff may get filled repeatedly.
Have you overloaded operator+= yet? That would perform string concatenation I believe.
It could be handy in a while loop where buff gets filled more than once from the stream.