程序不会打印字符串数组C++

Program won't Print a string array C++

本文关键字:数组 C++ 字符串 打印 程序      更新时间:2023-10-16

我已经在这个程序上工作了一段时间,但是它拒绝在这最后一点上合作。该程序的重点是将数据文件筛选为三个数组,对数组进行排序,然后将它们打印到一个表中。我的问题似乎出在桌子上。该程序分为四个函数,当我尝试调试时,它不会在函数中显示productName数组。

出现故障的代码段如下所示:

void printReport (string productName[], int numberinStock[], float price[], int number_of_products)
{
    float totalPrice; 
    cout << setw(18) << " " << "Friendly Grocer Store Inventory" << setw(17) << " " << endl; 
    cout << setw(18) << "Inventory Item" << setw(16) << "Number in Stock" << setw(16) << "Unit Price" << setw(16) << "Total Sales" << endl; 
    for (int count=0; count <number_of_products-1; count++)
    {
        cout << setw(18) << productName[count] << setw(16) << numberinStock[count] << setw(16) << std::setprecision(2) << price[count] << setw(16) << std::fixed << std::setprecision(2) << price[count]*numberinStock[count] << endl; 
    }
    cout << "Total Price:  " << totalPrice; 
}

它将打印其他所有内容,但不打印productName。在for循环之外的一些调试语句,如cout << productName[1],将打印出适当的productName,但在实际报告中它完全是空白的。经过一些调试之后,似乎在for循环中打印productName之后的每个项都覆盖了产品名称。

例如只留下cout << setw(18) << productName[count] << setw(16) << numberinStock[count] << endl;

将产生

" 3 s "
" 10 h"
" 2a"

产品名称有芒果、三明治和披萨。

我很茫然。我哪里搞砸了?

您可能把数据传递给函数时搞砸了。如果在函数中设置了测试数组,则应该可以正确打印。

在c++中使用arrayname传递数组。如

int main ()
{
  string productName[] = {"mango"}; 
  ...
  printReport(productName, numofProduct);
  return 0;
}