2012-02-28 83 views
1

Im在C++中遇到一些麻煩。 請參閱我想讓用戶以String的形式給程序一個輸入,並繼續這樣做直到用戶滿意爲止。我的輸入工作正常,但是當我想將字符串存儲到一個數組即時運行一些問題。我必須爲我的數組顯然定義一個大小?並有沒有辦法將輸入存儲在2或3個不同的arrays(取決於輸入,我用一些if語句排序),並將它們打印出來? 我的代碼看起來現在這個樣子..將字符串添加到未知大小的數組C++

string firstarray[10]; 
string secarray[10]; 

//The cin stuff here and reading strings from user-input 

    if(MyCondition1){ 
for(int x = 0; x<=9;x++){ 
firstarray[x] = name; 
} 

    if(MyCondition2){ 
    for(int x = 0; x<=9;x++){ 
    secarray[x] = name; 
    } 

有沒有辦法跳過數組的10限制?它可以像字符串

firstarray[]; 

+1

你想用多個數組解決什麼問題? A vector firstArray;擺脫大小限制。 – 2012-02-28 14:40:32

+0

你的意思是'std :: string',對吧?我的意思是,我沒有在任何地方看到「使用命名空間」...... – 2012-02-28 14:40:48

+0

他在問題中使用了沒有std ::的字符串。 – BoBTFish 2012-02-28 14:43:57

回答

8

您正在查找std::list。或者更好,一個std::vector,它允許你通過他們的位置訪問元素。

兩者都可以動態擴展。

using namespace std; 

// looks like this: 
vector<string> firstvector; 

firstvector.push_back(somestring); // appends somestring to the end of the vector 

cout << firstvector[someindex]; // gets the string at position someindex 
cout << firstvector.back(); // gets the last element 

關於你的第二個問題:
當然,你可以創建多個陣列/矢量把你的字符串甚至使用map<key, vector<string>>類型,其中key可以爲枚舉的std::map類別(或字符串,but enum is better)。

你把一個新值的載體之一:

tCategoryEnum category = eCategoryNone; 
switch(condition) 
{ 
    case MyCondition1: 
    category = eCategory1; 
    break; 
    case MyCondition2: 
    category = eCategory2; 
    break; 
    // ... 
} 
// check if a category was found: 
if(category != eCategoryNone) 
{ 
    categoryMap[category].push_back(name); 
} 

然後輸出這一點,你可以簡單地遍歷每個類別和矢量元素

for(int i = 0; i < categoryMap.size(); i++) 
    for(int j = 0; j < categoryMap[i].size(); j++) 
    cout << categoryMap[i][j]; 
5

你有沒有使用std::vector<string> >考慮?

+0

我已經遇到它在一些谷歌結果。但我認爲這是「過度做」,猜測我錯了。有人可以鏈接一個方法嗎? – Handsken 2012-02-28 14:44:52

+1

@Handsken沒有辦法這麼做,矢量比數組更容易使用。看看馬丁的例子,它應該讓你走上正軌。 – Motti 2012-02-28 14:51:02