0
我有一個字符串。我想將其轉換爲字符串中提到的數據類型。
例如: string =>「int」。
現在我必須用字符串中的內容初始化一個變量。如何將字符串轉換爲C++中字符串中提到的數據類型
int value;
我該怎麼做?
我有一個字符串。我想將其轉換爲字符串中提到的數據類型。
例如: string =>「int」。
現在我必須用字符串中的內容初始化一個變量。如何將字符串轉換爲C++中字符串中提到的數據類型
int value;
我該怎麼做?
如果你的字符串包含這樣的事情: 「(類型)(分離器)(值)」,
例如,(如果分隔符爲 「$$$」): 「INT $$$ 132」 或「雙$ $$ 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 *
}
不知道這是否會解決您的整個問題,但只是一個開始:
#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;
}
由於類型是固定在編譯時,這隻會是可能的一些有限的,預先決定的清單類型,這取決於你想如何使用結果。你到目前爲止做了什麼嘗試? – BoBTFish
我嘗試過使用typedef,但它沒用。 –
是的,因爲'C++'是[*靜態類型*](http://en.wikipedia.org/wiki/Type_system#Static_type-checking),所以你不能選擇運行時變量的類型。你可以有一大堆調用定製函數的if語句:if(s ==「int」)intFoo()else if(s ==「float」)floatFoo()// ... '(或者''foo()','foo ()'等)。 –
BoBTFish