如果我给出10表示应该打印它是一个整数 如果我给10.2意味着它应该打印它是一个浮点数 如果我给'a'表示它应该打印它是一个字符
答案 0 :(得分:1)
首先以std::string
的形式读取输入。
然后,将字符串传递给std::stoi()
,如果它正确地使用了整个字符串,则输出结果整数。
否则,将字符串传递给std::stof()
,如果它正确使用了整个字符串,则打印结果浮点数。
否则,按原样打印字符串。
答案 1 :(得分:0)
您可以使用type_traits和模板专门化来实现。请参阅此示例以获取更多信息:-
#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;
}