2011-02-24 85 views
1

我有一個數組可以跟蹤三個並行陣列的搜索結果。平行數組是名稱,ID號和餘額。名稱與ID和平衡相關聯,因爲它們都具有相同的索引。用戶搜索名稱,程序應該將搜索結果輸出到名稱,ID和餘額的文本文件。所以現在每一個搜索成功時(該名稱在數組中),我那個名字的索引添加到一個名爲resultsAr一個數組,像這樣:基於另一個陣列的內容輸出三個陣列到文件

while(searchTerm != "done") 
{ 
    searchResult = SearchArray(searchTerm, AR_SIZE, namesAr); 

    if(searchResult == -1) 
    { 
     cout << searchTerm << " was not found.\n"; 
    } 
    else 
    { 
     cout << "Found.\n"; 
     resultsAr[index] = searchResult; 
     index++; 
    } 

    cout << "\nWho do you want to search for (enter done to exit)? "; 
    getline (cin,searchTerm); 

} // End while loop 

我無法弄清楚如何輸出這個,所以它只輸出找到的名字。現在我只是這樣做:

outFile << fixed << setprecision(2) << left; 
outFile << setw (12) << "Id#" << setw(22) << "Name" << "Balance Due" 
     << endl << endl; 

for(index = 0; index < sizes; index++) 
{ 
    outFile << left << setw (10) << idsAr[index] << setw(22) << namesAr[index] 
      << setw(3) << "$"; 
    outFile << right << setw(10) << balancesAr[index] << endl; 
} 

但顯然這只是輸出整個數組。我已經嘗試了一些東西,但我無法弄清楚我會做什麼,因此它只會輸出resultsAr中的那些東西。

謝謝,這是家庭作業,所以沒有確切的答案,這將是可怕的。

編輯:大寫問題並不是一個真正的問題,我只是不小心做到了這一點,當我在這裏張貼我想,對不起。 resultsAr部分正在工作,因爲在搜索數組的內容之後是我搜索的名稱的索引。該SearchArray()函數如下:

int SearchArray(string searchTerm, 
      int size, 
      string namesAr[]) 
{ 
// Variables 
int index; 
bool found; 

// Initialize 
index = 0; 
found = false; 

while(index < size && !found) 
{ 
    if(namesAr[index] == searchTerm) 
    { 
     found = true; 
    } 
    else 
    { 
     index++; 
    } 
} 

if(found) 
{ 
    return index; 
} 
else 
{ 
    return -1; 
} 
} 

回答

1

我的榮幸。現在我明白你在做什麼。你必須做的是使用另一種間接方式。您只想輸出存儲在resultsAr中的那些索引的結果。
更改您的for循環類似於這樣:

int numFound = index; 
for(index = 0; index < numFound; index++) { 
    cout << left << " "<<idsAr[resultsAr[index]]; 
} 

這意味着,第一家店你找到索引數(在while循環高於此),進入「numFound」。然後只遍歷0 ... numFound-1,並在訪問該元素時使用雙重間接;這意味着查看包含索引找到的resultsAr,然後使用該索引來查找實際數據。

+0

非常感謝,這非常有意義。你真棒。 – Michael 2011-02-24 11:31:06

1

貴SearchArray()函數返回在此匹配的字符串在指針數組發現爲字符串的第一個指數?然後將它存儲在只有一個入口的數組中?即使如此,您要存儲的元素是「SearchResult」(大寫),這是永遠不會定義的。

- >請發佈完整的源代碼(包括SearchArray())。

編輯:

好,感謝張貼SearchArray(),但我們仍然需要更多的,在第一個框中你寫:

resultsAr[index] = searchResult; 

...但沒有給我們一個循環。另外,如果你想找到多個與「searchTerm」匹配的名字,你將不得不編寫SearchArray()返回一個索引數組或者接受一個起始索引,否則它將多次返回首次發現的名字。

+0

對不起,我添加了整個代碼部分。非常感謝您的幫助。 – Michael 2011-02-24 10:17:01