Florian
Florian

Reputation: 29

Integer or double 1.0 and 1

I want to read a double number and determine if the input is Integer or double. The problem is that when I enter 1.00 (which is double) I get the result as integer

double a;
cin >> a;
if (a == int(a))
    cout << "Integer";
else
    cout << "Double";

Upvotes: 0

Views: 2470

Answers (3)

Aykhan Hagverdili
Aykhan Hagverdili

Reputation: 29985

You can read into a string and check if it contains the decimal separator. Assuming it is '.', here's an example implementation:

#include <iostream>
#include <string>

int main()
{
  std::string s;
  std::cin >> s;
  std::cout << ((s.find('.') == std::string::npos) ? "integer" : "double") << std::endl;
  return 0;
}

You also have to check for exponents (like 2e-1). Here's one way to do it all:

#include <iostream>
#include <string>

int main()
{
  std::string s;
  std::cin >> s;
  if (s.find_first_of(".,eE") == std::string::npos)
    std::cout << "integer" << std::endl;
  else
    std::cout << "double" << std::endl;
  return 0;
}

Upvotes: 3

schorsch312
schorsch312

Reputation: 5714

Perhaps std::variant is an elegant way to solve your problem. std::variant<int, double> can store both an int or a double. Dependent on what you store the internal type will change.

#include <variant>
#include <string>
#include <cassert>


bool isInt(const std::variant<int, double> &intOrDouble) {
    try {
      std::get<double>(intOrDouble); 
    }
    catch (const std::bad_variant_access&) {
        return false;
    }
    return true;
}

int main()
{
    std::variant<int, double> intOrDouble;
    intOrDouble = 12.0; // type will be double -> return will be 1
    //intOrDouble = 12; // type will be int    -> return will be 0

    return isInt(intOrDouble); 
}

Upvotes: 0

tswanson-cs
tswanson-cs

Reputation: 116

In your if statement you are casting a to an int. This is just going to truncate the decimal value.

1==1 is always true as is 1.0 == 1

I would suggest looking at this answer: How to validate numeric input C++

Upvotes: 2

Related Questions