I have a string. I want to convert that to datatype mentioned in string.
eg: string => "int".
now I have to initialize a variable with content in string.
int value;
How can I do this?
Do not know if this will solve your entire problem but just a start:
#include <iostream>
using namespace std;
template <class T>
class myType
{
public:
T obj;
void show()
{
cout << obj << endl;
}
};
void CreateType(char stype)
{
switch(stype)
{
case 'i':
myType<int> o ;
o.obj = 10;
cout << "Created int " << endl;
o.show();
break;
case 'd':
myType<double> o1 ;
o1.obj = 10.10;
cout << "Created double " << endl;
o1.show();
break;
}
}
int main()
{
CreateType('i');
CreateType('d');
return 0;
}
If your string contains something like this: "(type)(separator)(value)",
eg (if separator is "$$$"): "int$$$132" or "double$$$54.123" you should write a little parser.
const std::string separator = "$$$";
const unsigned int separatorLength = 3;
std::string str = "int$$$117";
std::string type, value;
unsigned int separatorPosition = str.find(separator);
type = str.substr(0, separatorPosition);
value = str.substr(separatorPosition + separatorLength);
void *variable;
if (type == "int"){
//convert value to int and store it in void *
} else
if (type == "double"){
//convert value to double and store it in void *
} else
if (type == "char"){
//convert value to char and store it in void *
}
C++is statically typed, you can't choose the type of a variable at run-time. You can have a bunch ofifstatements that call custom versions of a function though:if(s=="int") intFoo() else if (s=="float") floatFoo() // ...(or maybefoo<int>(),foo<float>(), etc).