Hi. Is your read function meant to read the entire content (not just 1 line) of the stream to an str ?
If so, there is a std::istream function which gives the # of characters in the stream, so you can allocate enough space up front. See http://www.cplusplus.com/reference/istream/istream/
Here's what I have, as a global (not member) function:
1 2 3 4 5 6 7 8 9 10 11 12
|
std::istream& read( std::istream& is, myStr& s )
{
s.clear();// a member function of myStr class
// get length of file:
is.seekg (0, is.end);
s.sz = is.tellg();// # chars in stream
is.seekg (0, is.beg);// reset to beginning
s.pStr = new char[s.sz+1];// I null term, so I need 1 extra
is.read( s.pStr, s.sz );
s.pStr[s.sz] = '\0';
return is;
}
|
I think this adapts to your case here:
1 2 3 4 5 6 7 8 9 10 11
|
std::istream& str::read( std::istream& is )
{
if( currStr ) delete [] currStr;
// get length of file:
is.seekg (0, is.end);
currPlace = is.tellg();// # chars in stream
is.seekg (0, is.beg);// reset to beginning
currStr = new char[currPlace];// no extra for '\0'
is.read( currStr, currPlace );
return is;
}
|
The harder one for me was
std::istream& getline( std::istream&, char delim = '\n' );
due to inability to know the stream size before reading from it. I used an approach similar to what you're attempting, but with a larger char array to serve as an input buffer.
Here's mine, again as a global function:
1 2 3 4 5 6 7 8 9 10 11 12 13 14
|
std::istream& getline( std::istream& is, myStr& s, char delim = '\n' )
{
const int buffSz = 6;// make bigger after testing
char buff[buffSz];
s.clear();
// read into buff. Append buff to s
while( is.get( buff, buffSz, delim ) ) s += buff;
std::cin.clear();
std::cin.ignore( 256, '\n' );
return is;
}
|
That code uses a couple of function you may not have written yet.
1. A constructor taking const char* as an argument. A string should be constructable from a string literal, ie
str myName("Joe Dirt");
This is a good ctor to have:
str(const char*);
2. Overload operator +=, or write an append function.
Then you can write:
while( is.get( buff, buffSz, '\n' ) ) s += buff;// relies on new ctor
or
while( is.get( buff, buffSz, '\n' ) ) s.append(buff);