如何将字符串转换为c ++中字符串中提到的数据类型

时间:2013-10-29 09:07:44

标签: c++ c string type-conversion

我有一个字符串。我想将其转换为字符串中提到的数据类型 例如: string => “INT”。
现在我必须使用string中的内容初始化变量。

int value;

我该怎么做?

2 个答案:

答案 0 :(得分:1)

不知道这是否能解决您的整个问题,只是一个开始:

#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;   
}

答案 1 :(得分:0)

如果您的字符串包含以下内容:“(type)(separator)(value)”,

例如(如果分隔符是“$$$”):“int $$$ 132”或“double $$$ 54.123”你应该写一个小解析器。

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