简体   繁体   中英

Program won't Print a string array C++

I have been working on this program for awhile, but it refuses to cooperate on this last little stretch. The point of the program is to sift a data file into three arrays, sort the arrays, then print them out into a table. The problem I'm having appears to be with the table. The program is divided into four functions, and when I attempt to debug, it won't show the productName array in the function.

The malfunctioning segment of code looks like this:

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; 
}

It will print everything else, but not the productName . Some debugging statements outside of the for loop like cout << productName[1] will print out the proper productName but it's completely blank on the actual report. After some debugging it seems like after printing the productName in the for loop every item after that overwrites the product name.

For example just leaving cout << setw(18) << productName[count] << setw(16) << numberinStock[count] << endl;

will produce

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

The product names there are Mangoes, Sandwich, and pizza.

I'm at a loss. Where did I mess up?

You might have screwed up passing the data into the function. If you set up test arrays in the function it should be printing correctly.

To pass arrays in C++ use the arrayname. eg

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM