'How to know float or integer? [closed]

there are 2, 2.0 or 2.55. How to know float or integer in C++.

I use ceil, floor and typeid functions, it always give me incorrect output

How can I do?

Code:

struct CalExp {
  char id[500];
};

double Operator( CalExp* op, int i, double num1, double num2 ) {
    if (strcmp(op[i].id, "*") == 0) return num1 * num2;
    else if (strcmp(op[i].id, "/") == 0) return num1 / num2;
    else if (strcmp(op[i].id, "+") == 0) return num1 + num2;
    else if (strcmp(op[i].id, "-") == 0) return num1 - num2;
    return 0.0;
} // Operator()

void Calculation( vector<Token> token ) { // math
    CalExp postfix[500] = { '\0' }; // Like 2 3 +
    ...
    int top = 0;
    float cal_array[200] = { 0.0 };
    for ( int i = 0; i < postfix_len; i++) {
        if ((strcmp(postfix[i].id, "+") == 0 ) || (strcmp(postfix[i].id, "-") == 0) ||
            (strcmp(postfix[i].id, "*") == 0 ) || (strcmp(postfix[i].id, "/") == 0)) {
            if (cal_array[top] == 0.0 && strcmp(postfix[i].id, "/") == 0) { // eg. 2/0
                cout << "ERROR";
                return;
            } // if
            cal_array[top - 1] = Operator( postfix, i, cal_array[top-1], cal_array[top]);
            top--;
        } // if
        
        else {
            cal_array[++top] = atof(postfix[i].id); 
        } // else
    } // for

  if ( /*has "." */ ) cout << setprecision(3) << fixed << cal_array[top];
  else cout << (int)cal_array[top];
c++


Solution 1:[1]

Since these are types in the system, you can use type traits:

auto v = 2;
std::cout << std::is_integral_v<decltype(v)> << "\n"; // true
std::cout << std::is_floating_point_v<decltype(v)> << "\n"; // false

If you want to check against a specific type, you can use is_same:

std::cout << std::is_same_v<decltype(v), int> << "\n"; // true
std::cout << std::is_same_v<decltype(v), std::uint8_t> << "\n"; // false

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Fantastic Mr Fox