Reputation: 1553
I have this code:
double i;
while(cin >> i)
{
if ( i < 0.0)
cout << "ENTER A POSITIVE NUMBER: ";
else
break;
}
I want code like this ( I don't want to use break):
while((cin >> i) < 0.0)
{
cout << "ENTER A POSITIVE NUMBER: ";
}
I get an error on this line: while((cin >> i) < 0.0)
saying invalid operands to binary expression
.
What am I missing?
Upvotes: 4
Views: 4879
Reputation: 8511
Do:
while( cin >> i && i < 0.0 )
{
cout << "ENTER A POSITIVE NUMBER: ";
}
The error is caused due to the fact that the expression (cin >> i)
is not valid for comparison with a double.
Upvotes: 0
Reputation: 7838
The return value of cin >> i
is the stream, not the read value. This is to allow chaining of operands
cin >> i >> j;
You could try this:
while( (cin >> i, i) < 0. )
{
cout << "ENTER A POSITIVE NUMBER: ";
}
The comma operator should return the value of i
but I haven't tested it.
EDIT: Don't use this approach, as David Rodríguez has noted this discards the result of the read. Use while( (cin >>i) && (i<0.) )
instead.
Upvotes: 2
Reputation: 5440
The expression (cin >> i)
does not return a double.
You can write the same statement, without a break
, as:
double i;
while ((cin >> i) && (i < 0.0)) {
cout << "ENTER A POSITIVE NUMBER: ";
}
Upvotes: 4
Reputation: 19790
you want to check the value of i, not the return of cin
while((cin >> i) && ( i < 0.0))
{
cout << "ENTER A POSITIVE NUMBER: ";
}
Upvotes: 4
Reputation: 3346
Use it like this.
while ((cin >> i) && (i < 0.0))
The overloaded function for cin
returns an object by reference of istream class
. So you cannot compare it to a double value.
cin >> i
|-------| //this is an object of istream class
Upvotes: 10