cpp get data type
#include <iostream>
using namespace std;
template <typename T>
void getDataType(T var) {
cout << "The data type is: " << typeid(var).name() << endl;
}
int main() {
int integerVar = 10;
double doubleVar = 3.14;
char charVar = 'A';
getDataType(integerVar);
getDataType(doubleVar);
getDataType(charVar);
return 0;
}
Explanation:
#include <iostream>
: Includes the input/output stream library that allows input and output operations.using namespace std;
: Specifies that the program will use the standard namespace, allowing access to functionality like cout.template <typename T> void getDataType(T var) {...}
: Defines a template functiongetDataType
that takes a parametervar
of a generic typeT
.cout << "The data type is: " << typeid(var).name() << endl;
: Outputs the message "The data type is: " along with the name of the type of the variablevar
.int main() {...}
: The main function where the program execution begins.int integerVar = 10; double doubleVar = 3.14; char charVar = 'A';
: Declares variablesintegerVar
,doubleVar
, andcharVar
of types int, double, and char respectively, and initializes them with values.getDataType(integerVar); getDataType(doubleVar); getDataType(charVar);
: Calls thegetDataType
function with the variablesintegerVar
,doubleVar
, andcharVar
as arguments to determine their respective data types using typeid.return 0;
: Indicates successful program execution by returning 0 to the operating system.