[英]how do I check the data type of the given input in cpp?
如果我給出 10 意味着它應該打印它是一個整數 如果我給出 10.2 意味着它應該打印它是一個浮點 如果我給出 'a' 意味着它應該打印它是一個字符
首先將輸入作為std::string
讀取。
然后,將字符串傳遞給std::stoi()
,如果它沒有錯誤地消耗整個字符串,則打印結果整數。
否則,將字符串傳遞給std::stof()
,如果它沒有錯誤地消耗整個字符串,則打印結果浮點數。
否則,按原樣打印字符串。
您可以使用 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;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.