2013-10-29 31 views
0

我有一個字符串。我想將其轉換爲字符串中提到的數據類型。
例如: string =>「int」。
現在我必須用字符串中的內容初始化一個變量。如何將字符串轉換爲C++中字符串中提到的數據類型

int value; 

我該怎麼做?

+3

由於類型是固定在編譯時,這隻會是可能的一些有限的,預先決定的清單類型,這取決於你想如何使用結果。你到目前爲止做了什麼嘗試? – BoBTFish

+0

我嘗試過使用typedef,但它沒用。 –

+2

是的,因爲'C++'是[*靜態類型*](http://en.wikipedia.org/wiki/Type_system#Static_type-checking),所以你不能選擇運行時變量的類型。你可以有一大堆調用定製函數的if語句:if(s ==「int」)intFoo()else if(s ==「float」)floatFoo()// ... '(或者''foo ()','foo ()'等)。 – BoBTFish

回答

0

如果你的字符串包含這樣的事情: 「(類型)(分離器)(值)」,

例如,(如果分隔符爲 「$$$」): 「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 * 
} 
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; 
} 
相關問題