Reputation: 162
I need to overloading the cin >> operator for my c string class. I have overloaded the operator before but don't understand how to do this dynamically without having the size before hand to create the c string.
This is for homework and I must not use the string class. I also have to use dynamic allocation.
This is what I have so far... I know it's probably very poorly written, forgive me I'm a beginner.
istream& operator>> (istream& is, MyString& s1)
{
MyString temp;
int size = 0;
int i = 0;
int j = 0;
while (isspace(temp.data[i]) == true) {
is.get(temp.data[i]);
i++;
}
while (isspace(temp.data[j]) != true) {
size++;
temp.grow(size);
is >> temp.data[j];
j++;
}
return is;
}
Upvotes: 0
Views: 1187
Reputation: 596307
Without seeing exactly how your MyString
class is implemented, we can only speculate about how best to implement streaming into it, but typically you should implement your custom operator>>
something like this:
istream& operator>> (istream& is, MyString& str)
{
istream::sentry s(is, false); // prepare the stream for input (flush output, skip leading whitespaces, error checking, etc)
if (s) // is the stream ready?
{
// clear str as needed
streamsize N = is.width();
if (N == 0) N = ... ; // set to max size of str, or numeric_limits<size_t>::max()
char ch;
while (is.get(ch)) // while not EOF or failure
{
// append ch to str, growing its capacity as needed
if (--N == 0) break; // max width reached?
if (!is.peek(ch)) break; // EOF reached?
if (isspace(ch, is.getloc()) break; // trailing whitespace detected?
}
}
is.width(0); // reset effect of std::setw()
return is;
}
The STL's built-in operator>>
implementation for std::string
is a little bit more complicated (use of traits and facets, direct access to the istream
read buffer, etc), but this is the jist of it, based on the following information from CppReference.com:
operator<<,>>(std::basic_string)
template <class CharT, class Traits, class Allocator> std::basic_istream<CharT, Traits>& operator>>(std::basic_istream<CharT, Traits>& is, std::basic_string<CharT, Traits, Allocator>& str);
Behaves as an FormattedInputFunction. After constructing and checking the sentry object, which may skip leading whitespace, first clears str with
str.erase()
, then reads characters from is and appends them to str as if bystr.append(1, c)
, until one of the following conditions becomes true:
- N characters are read, where N is is.width() if is.width() > 0, otherwise N is str.max_size()
- the end-of-file condition occurs in the stream is
-std::isspace(c,is.getloc())
is true for the next character c in is (this whitespace character remains in the input stream).If no characters are extracted then
std::ios::failbit
is set on is, which may throw std::ios_base::failure.Finally, calls
os.width(0)
to cancel the effects of std::setw, if any.
Upvotes: 3