Check if input is empty if input is declared as double [C ++]

I have three variables declared as paired:

double Delay1 = 0;
double Delay2 = 0;
double Delay3 = 0;

I Then get your values ​​from the user:

cout << "Please Enter Propogation Delay for Satellite #1:";  
cin >> Delay1;
...

But when I check these values ​​to see if they are zero (the user just hit enter and did not put the number), it does not work:

if(Delay1  || Delay2 || Delay3 == NULL)  
      print errror...

This is done every time.
What is the correct way to check if declared input is double, empty?

+3
source share
8 answers

Sort of

cin >> Delay1;
if(cin) { ... }

, cin . Enter. - .

3a

double, a, . cin a . , , . , , - , .

, , getline,

string delay;
if(!getline(std::cin, delay) || !isnumber(delay)) {
  ...
}

isnumber

bool isnumber(string const &str) {
  std::istringstream ss(str);
  double d;

  // allow leading and trailing whitespace, but no garbage
  return (ss >> d) && (ss >> std::ws).eof();
}

operator>> , std::ws . , eof. , , , cin.

, double double `isnumber, .


, operator void*, operator!, good(), fail(), bad() eof(), :

            flag | badbit  |  failbit  |  eofbit
function         |         |           |
-----------------+---------+-----------+--------
op void*         |    x    |     x     |
-----------------+---------+-----------+--------
op !             |    x    |     x     |
-----------------+---------+-----------+--------
good()           |    x    |     x     |    x
-----------------+---------+-----------+--------
fail()           |    x    |     x     |
-----------------+---------+-----------+--------
bad()            |    x    |           |
-----------------+---------+-----------+--------
eof()            |         |           |    x
-----------------+---------+-----------+--------

x, . operator void* bool (if(cin) ...), operator! , !cin

+11
std::cout << "Enter doubles: ";
std::cin >> d1 >> d2 >> d3;

if(std::cin.fail())
{
    // error!
}
+4

- :

if(!std::cin) throw "Doh!";

operator>> , :

if( std::cin >> Delay1 ) 
  good();
else
  bad();

, . , . , .

+3

, , double.

cin >> Delay1;
if (!cin.fail()) {
  // Input was a double
} else {
  // Input was something that could not be interpreted as a double
}

if (cin >> Delay1) {
  // Input was a double
} else {
  // Input was something that could not be interpreted as a double
}

, Delay1 , , , - . , "NULL", , .

+3

.

-: , , , if (cin.fail()) { /* print error */ }.

: Delay1 || Delay2 || Delay3 , - .

-: == NULL ( false) NULL. , true.

+2

if. if(Delay1 || Delay2 || Delay3 == NULL) , Delay , , delay2 , Delay3 . , . 0 . , . , epsilon.

+2

, , double.

if(!(std::cin >> Delay1 >> Delay2 >> Delay3)) {
    // error
}
+1

I think you need to read the variable as a string, and then check if it is empty, and then convert it to double (and check if it is a real double - the user can simply type "hello").

0
source

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


All Articles