0

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?

18
  • 3
    Since types are fixed at compile time, this will only be possible for some limited, pre-decided list of types, and it will depend on how you want to use the result. Have you made any attempt so far? Commented Oct 29, 2013 at 9:08
  • 2
    Yes, since C++ is statically typed, you can't choose the type of a variable at run-time. You can have a bunch of if statements that call custom versions of a function though: if(s=="int") intFoo() else if (s=="float") floatFoo() // ... (or maybe foo<int>(), foo<float>(), etc). Commented Oct 29, 2013 at 9:13
  • 1
    @Acme I think you may mislead the asker into thinking you can choose a template parameter at run-time. Commented Oct 29, 2013 at 9:24
  • 2
    What are you actually trying to do here? Commented Oct 29, 2013 at 9:27
  • 1
    What you describe looks like one solution. Please describe your problem in general terms; there is probably a better simpler solution. Commented Oct 29, 2013 at 9:28

2 Answers 2

1

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;   
}
Sign up to request clarification or add additional context in comments.

Comments

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 *
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.