【问题标题】:Outputting Three Arrays to a File Based on the Contents of Another Array根据另一个数组的内容将三个数组输出到一个文件
【发布时间】:2011-02-24 09:21:56
【问题描述】:

我有一个数组来跟踪三个并行数组的搜索结果。并行数组是名称、id#s 和余额。名称与 id 和 balance 相关联,因为它们都具有相同的索引。用户搜索名称,程序应该将搜索结果输出到包含名称、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;
}
}

【问题讨论】:

    标签: c++ arrays file


    【解决方案1】:

    我的荣幸。现在我明白你在做什么了。你所要做的是使用另一个间接。您只想为存储在 resultsAr 中的那些索引输出结果。
    将您的 for 循环更改为类似于以下内容:

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

    这意味着,首先将您找到的索引数量(在上面的 while 循环中)存储到“numFound”中。然后只遍历0...numFound-1,访问元素时使用双重间接;这意味着查看 resultsAr,其中包含找到的索引,然后使用该索引来查找实际数据。

    【讨论】:

    • 非常感谢,这很有意义。你太棒了。
    【解决方案2】:

    您的 SearchArray() 函数是否返回在指向字符串的指针数组中找到匹配字符串的第一个索引?然后将它存储在一个只有一个条目的数组中?即使是这样,您存储的元素也是从未定义过的“SearchResult”(大写)。

    -> 请发布完整的源代码(包括 SearchArray())。

    编辑:

    好的,感谢您发布 SearchArray(),但我们还需要更多,在您写的第一个框中:

    resultsAr[index] = searchResult;
    

    ... 但没有给我们一个循环。此外,如果您想找到与“searchTerm”匹配的 多个 名称,则必须编写 SearchArray() 或者返回一个索引数组或接受一个起始索引,否则它将返回第一个 -多次找到名称。

    【讨论】:

    • 对不起,我添加了整个代码部分。非常感谢您的帮助。
    猜你喜欢
    • 2019-12-26
    • 1970-01-01
    • 2013-08-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-07-26
    • 1970-01-01
    • 2016-07-19
    相关资源
    最近更新 更多