2012-06-25 20 views
0

例如,假設您從某處拉取數據並將其放入字符串變量中,則要使用其中的數據作爲另一個字符串名稱:在cpp/C++中使用字符串值數據聲明變量名稱

int main(void){ 

    string strVar ="StringData"; //this is a string variable with text inside 

    cout<<strVar<<endl; //displaying the variables contents 


    string strVar.c_str() = "stuff in string variable 'StringData'"; //this uses what was inside of strVar to be the name of the new string variable 

    cout<<StringData<<endl; //prints the contents of the variable StringData (who got its name from the data inside of strVar 
} 

//OUTPUT: 
StringData 
stuff in string variable 'StringData' 

我知道你絕對不能這樣做,在這個例子中,你必須事先知道在使用變量StringData之前什麼是strVar,但理論上可以這樣做嗎?

編輯:

謝謝大家,所以我想從你全部搞定,基本上它的不可能的,C++是不是一個動態變量的語言,我可以得到它最接近的是,能與 地圖(字符串,字符串)

+1

可能是'map '是你想要的嗎? – nhahtdh

+0

簡短的回答:不,這是不可能的。 – Marlon

回答

2

沒有明確的想法,但也許你會對std::map感興趣?聽起來像你想要的是一個鍵 - 值配對。

參考性病::地圖 - > http://www.cplusplus.com/reference/stl/map/

例子:

#include <map> 
#include <string> 
#include <iostream> 
using namespace std; 

int main(void) 
{ 
    map<string, string> myMap; 
    myMap.insert(pair<string, string>("StringData", "Stuff in StringData")); 

    // Get our data 
    cout << myMap["StringData"] << endl; 

    return 0; 
} 
+0

謝謝,虐待嘗試,看看它是否能解決我的問題 – Tech

0

變量名只存在於C++編譯時。最接近你可以使用帶有字符串鍵的地圖。

+0

那麼,生病了,必須認真反思我的方案,然後,感謝您的幫助@Antimony – Tech

0

我不確定你在問什麼,但是如果你想擁有「動態」變量名,那麼你不能直接在代碼中這樣做。你將不得不使用一些地圖類型的數據結構。如果您可以使用標準庫,請參閱std::hash_setstd::map

0

語言,你可以動態地創建變量。 C++不是其中之一;)