Negative value input during C ++ loop

I have this code:

double i; while(cin >> i) { if ( i < 0.0) cout << "ENTER A POSITIVE NUMBER: "; else break; } 

I need 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?

+4
source share
5 answers

The expression (cin >> i) does not return double.

You can write the same statement without break , like:

 double i; while ((cin >> i) && (i < 0.0)) { cout << "ENTER A POSITIVE NUMBER: "; } 
+4
source

Use it like that.

 while ((cin >> i) && (i < 0.0)) 

The overloaded function for cin returns an object by reference to the istream class . Therefore, you cannot compare it with a double value.

 cin >> i |-------| //this is an object of istream class 
+10
source

you want to check i value, not cin return

 while((cin >> i) && ( i < 0.0)) { cout << "ENTER A POSITIVE NUMBER: "; } 
+4
source

The return value cin >> i is a stream, not a read value. This means that the operand chain

 cin >> i >> j; 

You can try the following:

 while( (cin >> i, i) < 0. ) { cout << "ENTER A POSITIVE NUMBER: "; } 

The comma operator should return the value i , but I have not tested it.

EDIT: Do not use this approach, as David Rodriguez noted that this discards the reading result. Use while( (cin >>i) && (i<0.) ) Instead.

+2
source

make:

 while( cin >> i && i < 0.0 ) { cout << "ENTER A POSITIVE NUMBER: "; } 

The error is caused by the fact that the expression (cin >> i) not valid for comparison with a double.

0
source

Source: https://habr.com/ru/post/1439458/


All Articles