2011-02-24 86 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