简体   繁体   中英

Problem determining if input is integer C++

I am writing a function that determines if input corresponds to a desired type (int, double, float)

Here is my code so far:

My problem comes when I test for int input. Input as 4.0, where all the decimals are equal to 0 are not accepted.

How can I get around this?

#include<iostream>
#include<string>
#include<sstream>

template <typename T>
bool is_type(std::string Input)
{
    std::stringstream ss(Input);
    T test;
        std::string remainder;
    if (ss >> test)
    {
        ss >> remainder;
        return (remainder.size() == 0) ? true : false;
    }
    else return false;
}

   int main(void)
{
    std::string Input;;
    std::getline(std::cin, Input);

    if (is_type<int>(Input)) std::cout << "It is valid input.\n";

    return 0;
}    

"4.0" is a valid representation of an integer, namely, the digit character "4", followed by some other stuff. When you read that text into an int you get a valid value, and the rest of the input is left behind.

If you want to interpret the entire string as a numeric value, and treat the result as an integer when it has no fractional part, you have to read the entire input as a floating-point value. If the result is an integer value, then you have an integer; otherwise, you don't.

double d;
std::cin >> d;
if (d == (int)d)
    std::cout << "got an integer value.\n";
else
    std::cout << "didn't get an integer value.\n";

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM