When instead of operator !=
, <<
is considered, such error can be removed by including <string>
header.
But this doesn't seem to work on operator !=
.
So, I thought may be this error is due to difference in type of the variables I'm comparing.
So I considered type casting.
Here is what I'm trying to do :
while ( (cin >> value) != 0) { ... }
The type of value is int
.
Some options that I considered are:
value
isn't a pointerreinterpret_cast
: sameWhat other options do I have?
You can suggest some alternatives as well but I would like to know how to make it work.
The resultant value of (cin >> value)
is not the contents of value
, but rather cin
. cin
can be evaluated in a boolean context but doesn't compare to the int
, hence the compilation error.
You can modify the line to be (using the comma operator);
while ( (cin >> value, value) != 0)
The resultant here is the second operand of the comma operator, hence the value
. In turn it will compare with the 0
correctly. Although this now forgoes the validity tests on the cin
stream.
Demo.
Whilst a minimal change is presented above, the code itself tends to be obscure and misses some error checking. It is better to refactor the condition and provide more checks for errors in cin
;
while ( (cin >> value) && (value != 0) ) {
//...
}
Demo.
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments