简体   繁体   English

如何在 cpp 中检查给定输入的数据类型?

[英]how do I check the data type of the given input in cpp?

如果我给出 10 意味着它应该打印它是一个整数 如果我给出 10.2 意味着它应该打印它是一个浮点 如果我给出 'a' 意味着它应该打印它是一个字符

Read the input as a std::string first.首先将输入作为std::string读取。

Then, pass the string to std::stoi() , and if it consumes the whole string without error, print the resulting integer.然后,将字符串传递给std::stoi() ,如果它没有错误地消耗整个字符串,则打印结果整数。

Otherwise, pass the string to std::stof() , and if it consumes the whole string without error, print the resulting float.否则,将字符串传递给std::stof() ,如果它没有错误地消耗整个字符串,则打印结果浮点数。

Otherwise, print the string as-is.否则,按原样打印字符串。

You can use type_traits and template specialization to achieve this.您可以使用 type_traits 和模板特化来实现这一点。 Please see this example for more info:-请参阅此示例以获取更多信息:-

#include <iostream>
#include <type_traits>

template<typename T>
struct is_integer{
    static const bool value = false;
};

template<>
struct is_integer<int>{
    static const bool value = true;
};

template<typename T>
struct is_char{
    static const bool value = false;
};

template<>
struct is_char<char>{
    static const bool value = true;
};

template<typename T>
void printType(T t){
    if(is_integer<T>::value)
    {
        std::cout<<"Value is integer"<<std::endl;
    }
    else if(is_char<T>::value)
    {
        std::cout<<"Value is char"<<std::endl;
    }
    else if(std::is_floating_point<T>::value)
    {
        std::cout<<"Value is float"<<std::endl;
    }
}

int main()
{
    int i = 10;
    char j = 'a';
    float k = 10.2f;

    printType(i);
    printType(j);
    printType(k);

    return 0;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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