Home > Blockchain >  Overloading the stream extraction operator - Invalid operands to binary expression
Overloading the stream extraction operator - Invalid operands to binary expression

Time:11-02

trying to overload the extraction operator in this class

class Mystring {
    
private:
    
    char* cstring;
    size_t size;

public:

    friend std::istream &operator>>(std::istream &is, Mystring &str);

the function:

#include <iostream>
#include "mystring.h"

std::istream &operator>>(std::istream &is, Mystring &obj) {
    char *buff = new char[1000];
    is >> buff;                  /* Invalid operands to binary expression ('std::istream' (aka 'basic_istream<char>') and 'char *') */
    obj = Mystring{buff};
    delete [] buff;
    return is;
}

the error I get is: Invalid operands to binary expression ('std::istream' (aka 'basic_istream<char>') and 'char *')

when I tried to do something like this: is >> *buff;

It reads only the first char

Mystring name;
std::cout << "name: " << std::endl;
std::cin >> name;
std::cout << "Your name is " << name;
name: harry
Your name is h

CodePudding user response:

You get the error because the overload reading into a CharT*:

template< class CharT, class Traits>
basic_istream<CharT, Traits>&
  operator>>( basic_istream<CharT, Traits>& st, CharT* s );

was removed in C 20. In C 20, the closest you can get is to read into an array of known extent, using the new overload:

template< class CharT, class Traits, std::size_t N >
basic_istream<CharT, Traits>&
  operator>>( basic_istream<CharT, Traits>& st, CharT (&s)[N] );

which in this case could be used by declaring buff as an array instead of a pointer:

std::istream &operator>>(std::istream &is, Mystring& obj) {
    if(char buff[1000]; is >> buff)
        obj = Mystring{buff};
    return is;
}

I however suggest that you use a std::string instead of this pair:

char* cstring;
size_t size;

CodePudding user response:

Well, istream formatted input does not support reading strings into char* buffers, should it read a single character? a word? a line? everything up to EOF? After all, it doesn't know how large the buffer is.

You should use either

  • read(buffer,count) to read exactly count characters, waiting until they are available or until EOF.
  • auto num_read = readsome(buffer,count) to read up to count characters, without blocking so it might return num_read<count.
  • Related