C++ Input Overload Error - c++

istream& operator>>(istream& input, const complex& P) {
input >> P.real >> P.imaginary;
return input;
}
I have the code above and for some reason I get this error:
Invalid operands to binary expression ('istream' (aka 'basic_istream<char>') and 'double').
complex& P is an object which basically stores the real number part and imaginary number part of a complex number. So if you have 2 + 3i, P.real will return to you back 2 and P.imaginary will return to you back 3. And the real and imaginary numbers are both double.
Can someone help me figure this out?

When overloading the >> operator, the variable to which you want to assign the input values has to be mutable, so you need to remove the "const"
istream& operator>>(istream& input, complex& P) {
input >> P.real >> P.imaginary;
return input;
}

Related

Why can't I input an integer from the istream? *Error on starred input operators*

istream& operator>>(istream& is, State& s){
uint16_t first;
int second;
char delim;
is **>>** first >> delim >> second >> delim; //For player in Room.
for(GameObject* i : GameObject::GameObjects){
is **>>** first >> delim >> second >> delim;
s.containerObjects.insert(pair<int, int>(first, second));
}
s.containerObjects.insert(pair<int, int>(first, second));
return is;
}
The starred input operators are giving me an error from clang: 'Invalid operands to binary expression (std::istream and uint16_t).
The data in the file looks like so:
0:1|2:2|3:4|
Can anyone help me to understand why?
Thanks!
Edit: Original operator usage:
file >> currentState;
Error message: 'Invalid operands to binary expression (std::istream and uint16_t) says it all. There is no >> operator defined for type uint16_t. Try >> into a normal int type and then static_cast<unint16_t> the value and put it in your variable "first".
I didn't include iostream... however I was still able to use istream and ostream with basic strings, so I guess that is a built in thing?

while (cin>> struct str) in c++ how can I use?

I'm having a trouble when I use while(cin) with struct. Would someone please make me clear about this problem? I don't know whether this kind of post was asked or not. If it was please forgive me and my bad english as well.
struct ThiSinh{
string m_HT;
float m_H;
};
I overload operator >> for it
bool operator >> (istream& is, ThiSinh &ts){
getline(is, ts.m_HT);
is >> ts.m_H;
is.ignore();
return ???;
}
Because while (cin >> ThiSinh) require a bool type, so I dont know what number or data it should return. And how to break the while loop when I press ctrl + Z.
I have also tried
while(cin){
ThiSinh ts;
cin >> ts;
}
and it worked but I dont want to get that false data. So someone please helps me out. Thanks in advance.
Your operator >> returns a bool, which is extremely unusual for a stream extraction operator, and renders it unusuable in most streaming contexts. Such operators are expected to return a reference to the stream on which they operate:
istream& operator >> (istream& is, ThiSinh &ts){
getline(is, ts.m_HT);
is >> ts.m_H;
is.ignore();
return is;
}
This is how multiple exrtactions actually work:
std::cin >> a >> b >> c;
Effectively, this first does auto &tmp = operator>>(std::cin, a), and then calls operator>>(tmp, b), and so on.
The reason why streams (and by extension, stream extraction operations) can be used in conditionals is that std::istream (and std::ostream) defines a conversion to bool (which returns true iff the stream is in error-free state); that conversion is then invoked by the conditional.
In other words, this:
while (std::cin >> ts)
effectively becomes this:
while (static_cast<bool>(operator>>(std::cin, ts)))
and the cast is possible because operator>> returns std::istream& and std::istream defines a conversion to bool.

Overloaded input operator failing automated simple input test

So I'm failing a simple input test for one of assignment questions. I'm to parse two integers separated by a white space. The two integers are used in the private members num and denom of the Rationalnumber type I have defined as a class. Is there something obviously unconventional I am using in or missing from this code? This code works for all my tests.
std::istream &operator>>( std::istream &is, Rationalnumber &r ) {
Rationalnumber::in++; // increment counter
// get the num
string n;
getline(cin,n,' ');
stringstream ssnum(n);
ssnum >> r.num;
// get the denom
string d;
getline(cin,d,'\n');
stringstream ssdenom(d);
ssdenom >> r.denom;
return is;
}
Your code fails in, at least, two obvious ways:
If a different whitespace than space is used, e.g., '\t', it isn't recognized by your code.
The input operator doesn't indicate failure when it is given invalid inputs, e.g., when the input is "a b" rather than numbers.
Conventionally, when input fails, the valuevread remains unchanged. This is also not true for your implementation. To fix things up the code can actually be simplified and made a lot fadter in the process. As this is clearly a homework assignment I don't think it is appropriate to provide the code, though.
This code passes the test!:
std::istream &operator>>( std::istream &is, Rationalnumber &r ) {
Rationalnumber::in++; // increment counter
int in;
is >> in;
r.numerator(in);
is >> in;
r.denominator(in);
return is;
}

Override >> operator like int

this is part of a homework assignment. I don't want an answer just help. I have to make a class called MyInt that can store any sized positive integer. I can only use cstring cctype iomanip and iostream libraries. I really don't understand even where to begin on this.
6) Create an overload of the extraction operator >> for reading integers from an input stream. This operator should ignore any leading white space before the number, then read consecutive digits until a non-digit is encountered (this is the same way that >> for a normal int works, so we want to make ours work the same way). This operator should only extract and store the digits in the object. The "first non-digit" encountered after the number may be part of the next input, so should not be extracted. You may assume that the first non-whitespace character in the input will be a digit. i.e. you do not have to error check for entry of an inappropriate type (like a letter) when you have asked for a number.
Example: Suppose the following code is executed, and the input typed is " 12345 7894H".
MyInt x, y;
char ch;
cin >> x >> y >> ch;
The value of x should now be 12345, the value of y should be 7894 and the value of ch should be 'H'.
The last state of my code is as follows:
istream& operator>>(istream& s, MyInt& N){
N.Resize(5);
N.currentSize=1;
char c;
int i = 0;
s >> c;
N.DigitArray[i++] = C2I(c);
N.currentSize++;
c = s.peek();
while(C2I(c) != -1){
s >> c;
if(N.currentSize >= N.maxSize)
N.Resize(N.maxSize + 5);
N.DigitArray[i] = C2I(c);
i++;
N.currentSize++;
}
}
It almost works! Now it grabs the right number but it doesn't end when I hit enter, I have to enter a letter for it to end.
You can create an operator>> overload for your class this way (as a free function, not inside the class):
std::istream& operator>>(std::istream& lhs, MyInt& rhs) {
// read from lhs into rhs
// then return lhs to allow chaining
return lhs;
}
You can use the members peek and read of istream to read in characters, and isspace to test if a character is a space, and isdigit to check if a character is a number (isspace and isdigit are in the <cctype> header).
First of all, your operator>> should be concerned only with extracting the sequence of chars from the stream and knowing when to stop based on your rules for that. Then, it should defer to a constructor of myInt to actually ingest that string. After all, that class will probably want to expose constructors like:
myInt bigone ("123456123451234123121");
for more general-purpose use, right? And, functions should have a single responsibility.
So your general form will be:
istream& operator>> (istream& is, myInt x)
{
string s = extract_digits_from_stream(is);
x = myInt(s);
return is; // chaining
}
Now how do you extract just digits from a stream and stop at a non-digit? Well, the peek function comes to mind, as does unget. I'd look at source code for the extraction operator for regular integers and see what it does.

Problems overloading the >> Operator

I have the following block of code trying to overload the >> operator:
istream &operator >> (istream &stream, const Currency &obj){
cout << "Dollars: ";
stream>>obj.dollars;
cout<< "Cents: ";
stream>> obj.cents;
return stream;
}
But when I call cin>>newMoney from my main program it keeps repeating "DOLLARS:" over and over again in an endless loop like below:
Any ideas why?
I bet you have a Currency constructor that takes an 'int'. So stream>>obj.dollars; is the same as stream>>Currency(obj.dollars);. The function you pasted outputs "Dollars: " and then calls itself, outputting "Dollars: " again and then repeating forever.
I'd suggest making the constructor explicit so it doesn't misfire on you.
There is no enough information in your code (as of now). Till you post more code, all I can say is this, which is also important for you to note down: since you overload >> to take input, the object obj should be passed by non-const reference, so remove const from the second parameter, and make it look like this:
istream &operator >> (istream &stream, Currency &obj)