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
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;