Hello everyone im not very good with using pointers, maybe just need more explanation of using them/how i would change my code.
Well i have to update this program i have to read in item number cost and qusantity from a file instead of getting it from the user. the first line of the file is 3 which is the number of items that would be in the array.
next i have to convert my arrays over to pointer notation. What would be the best way to do this with my program/ how would i do it?

#include <iostream>
#include <iomanip>
#include <fstream>
using namespace std;

//global constants
const int NUM_ITEMS = 10; //number of items in the arrays

//function prototypes
void intro();
void readData(int itemNumbers[], double itemPrices[], int itemQuantity[], const int arraySize);
void sortData(int itemNumbers[], double itemPrices[], int itemQuantity[], const int arraySize);
void printData(const int itemNumbers[], const double itemPrices[], const int itemQuantity[], const int arraySize);
int searchData(const int itemNumbers[], int searchValue, const int arraySize);
void searchLoop(const int itemNumbers[], const double itemPrices[], const int itemQuantity[]);

/*
 * Main
 */
int main() {
    //declare variables
    int itemNumbers[NUM_ITEMS]; //holds the item numbers
    double itemPrices[NUM_ITEMS]; //holds the item prices
    int itemQuantity[NUM_ITEMS]; //holds the item quantity


    //Welcome message to user
    intro();

    //get user input
    //message to user
    cout << "Enter an item number, quantity, and price for " << NUM_ITEMS
            << " items." << endl << endl;

    //read in the data from the user
    readData(itemNumbers, itemPrices, itemQuantity, NUM_ITEMS);

    //sort the data
    sortData(itemNumbers, itemPrices, itemQuantity, NUM_ITEMS);

    //print the data in table format
    printData(itemNumbers, itemPrices, itemQuantity, NUM_ITEMS);

    //search for an item number and display its cost and quantity
    searchLoop(itemNumbers, itemPrices, itemQuantity);

    return 0;
}

/*
 * Function: intro
 * Description: Displays an intro message to the user
 */
void intro() {
    //Program introduction
    // \n and endl wanted to practice with both.
    cout << "*****************************************" << endl
            << "** Welcome to Program 1                ** \n"
            << "** Created by: Brandon                 ** \n"
            << "** Sorting and Searching Arrays        **" << endl
            << "*****************************************" << endl << endl;
}

/*
 * Function: readData
 * Description: Retrieves 10 item numbers, their price and quantity
 * from the user and stores their answers in 3 parallel arrays.
 */
void readData(int itemNumbers[], double itemPrices[], int itemQuantity[], const int arraySize) {

    //define input stream object
    ifstream inputFile;
    //open the file
    inputFile.open("inventoryData.txt");

    //close the file
    inputFile.close();
}

/*
 * Function: sortData
 * Description: Sorts 3 arrays in parallel, in ascending order.
 */
void sortData(int itemNumbers[], double itemPrices[], int itemQuantity[], const int arraySize) {

    //variables
    int numbersTemp, quantityTemp;
    double pricesTemp;
    bool swap;

    do {
        swap = false;
        for (int count = 0; count < arraySize - 1; count++) {
            if (itemNumbers[count] > itemNumbers[count + 1]) {
                numbersTemp = itemNumbers[count];
                quantityTemp = itemQuantity[count];
                pricesTemp = itemPrices[count];

                itemNumbers[count] = itemNumbers[count + 1];
                itemPrices[count] = itemPrices[count + 1];
                itemQuantity[count] = itemQuantity[count + 1];

                itemNumbers[count + 1] = numbersTemp;
                itemPrices[count + 1] = pricesTemp;
                itemQuantity[count + 1] = quantityTemp;

                swap = true;
            }
        }
    } while (swap);
}

/*
 * Function: printData
 * Description: prints the values of 3 arrays in table format
 */
void printData(const int itemNumbers[], const double itemPrices[], const int itemQuantity[], const int arraySize) {

    //set the header for the table
    cout << "|" << setw(20) << "Item Numbers" << setw(5) << "|" << setw(17)
            << "Item Prices" << setw(6) << "|" << setw(20) << "Item Quantity" << setw(4) << "|" << endl
            << "=========================================================================" << endl;
    //print the data from the arrays
    for (int count = 0; count < arraySize; count++) {
        cout << "|" << setw(13) << itemNumbers[count]
                << setw(12) << "|" << setw(13) << fixed << setprecision(2) << itemPrices[count]
                << setw(10) << "|" << setw(13) << itemQuantity[count] << setw(11) << "|" << endl
                //end of each row include a line
                << "-------------------------------------------------------------------------" << endl;
    }
}

/*
 * Function: searchData
 * Description: Search data is a binary search that accepts and array
 * and a search value, it then searches the array with the search value
 * and returns the values position in the array  or  -1 if its not in the array
 */
int searchData(const int itemNumbers[], int searchValue, const int arraySize) {

    int low = 0;
    int high = arraySize - 1;
    int mid;

    while (low <= high) {
        mid = (low + high) / 2;

        if (searchValue == itemNumbers[mid]) {
            return mid;
        } else if (searchValue > itemNumbers[mid]) {
            low = mid + 1;
        } else {
            high = mid - 1;
        }
    }

    return -1;
}

/*
 * Function: searchLoop
 * Description: Asks the user to search for a number or exit(loop)
 * when a number is inputed it will call the searchData() function
 * and will print out the results for that search.
 */
void searchLoop(const int itemNumbers[], const double itemPrices[], const int itemQuantity[]) {

    // Declare variables
    int result = 0; //holds search result
    int searchValue = 0; //holds search input from user

    //search for an item number and display its cost and quantity
    do {

        //start on a new line
        cout << endl << endl;
        cout << "Enter an item number to search or negative number to exit: ";
        cin >> searchValue;

        //if searchValue is less than 0 quit loop
        if(searchValue < 0){
            break;
        }

        //search for the item number the user entered   
        result = searchData(itemNumbers, searchValue, NUM_ITEMS);


        //check to see if the search returned a result.
        if (result == -1) {

            //Search did not return any results
            cout << "\n No results found..." << endl;

        } else if (result >= 0) //returned a result
        {

            cout << "Search results for item number " << searchValue << " :" << endl << endl;

            //set the header for the table
            cout << "|" << setw(17) << "Item Prices" << setw(6) << "|"
                    << setw(20) << "Item Quantity" << setw(4) << "|" << endl
                    << "================================================" << endl;

            //output the price and quantity
            cout << "|" << setw(13) << fixed << setprecision(2) << itemPrices[result]
                    << setw(10) << "|" << setw(13) << itemQuantity[result]
                    << setw(11) << "|" << endl

                    //end of each row include a line
                    << "------------------------------------------------" << endl;

        }

    } while (searchValue >= 0);

}

the text file i need to get data from is this
inventoryData.txt

3
39284 5.75 12
18372 4.50 23
27649 12.99 81

Recommended Answers

All 4 Replies

Basically, instead of having a stack allocated array of some size, you need to allocate the array on the heap. Allocating via new[] will give you a pointer to the data. However, there is one downside.. You must now delete[] the array after you're done using it!

For example:

#include <fstream>
#include <iostream>

void ReadFile(int* LinesRead, int** ItemNumbers, double** Prices, int** Quantities)
{
    std::fstream File("inventoryData.txt", std::ios::in);
    if (File.is_open())
    {
        File >> *LinesRead; //Store the amount of lines read into the variable.
        *ItemNumbers = new int[*LinesRead]; //Allocate "LinesRead" integers.
        *Prices = new double[*LinesRead];   //Allocate "LinesRead" doubles.
        *Quantities = new int[*LinesRead];  Allocate "LinesRead" integers.

        for (int i = 0; i < *LinesRead; ++i)
        {
            File >> (*ItemNumbers)[i] >> (*Prices)[i] >> (*Quantities)[i];
        }

        File.close();
    }
}


int main()
{
    int LinesRead = 0;
    int* ItemNumbers = NULL; //Pointer to integers
    double* Prices = NULL;   //Pointer to doubles
    int* Quantities = NULL;  //Pointer to integers

    ReadFile(&LinesRead, &ItemNumbers, &Prices, &Quantities); //Pass the address of each pointer.

    for (int i = 0; i < LinesRead; ++i)
        std::cout<<"Item#: "<<ItemNumbers[i]<<" Price: "<<Prices[i]<<" Quantity: "<<Quantities[i]<<"\n";

    delete[] ItemNumbers;
    delete[] Prices;
    delete[] Quantities;
}

That is the same as the below (which uses references instead):

#include <fstream>
#include <iostream>

void ReadFile(int &LinesRead, int* &ItemNumbers, double* &Prices, int* &Quantities)
{
    std::fstream File("inventoryData.txt", std::ios::in);
    if (File.is_open())
    {
        File >> LinesRead;
        ItemNumbers = new int[LinesRead];
        Prices = new double[LinesRead];
        Quantities = new int[LinesRead];

        for (int i = 0; i < LinesRead; ++i)
        {
            File >> ItemNumbers[i] >> Prices[i] >> Quantities[i];
        }

        File.close();
    }
}


int main()
{
    int LinesRead = 0;
    int* ItemNumbers = NULL;
    double* Prices = NULL;
    int* Quantities = NULL;

    ReadFile(LinesRead, ItemNumbers, Prices, Quantities);

    for (int i = 0; i < LinesRead; ++i)
        std::cout<<"Item#: "<<ItemNumbers[i]<<" Price: "<<Prices[i]<<" Quantity: "<<Quantities[i]<<"\n";

    delete[] ItemNumbers;
    delete[] Prices;
    delete[] Quantities;
}

Which one to use is up to you.. Both do the same thing..

this is what i have so far but having troubles with getting the right data into the right array not sure how i would do that never worked with file stream before.

#include <iostream>
#include <iomanip>
#include <fstream>
#include <cstdlib>
using namespace std;


//function prototypes
void intro();
void getArraySize(int *sizePointer, ifstream &inFile);
void readData(int *numbersPointer, double *pricesPointer, int *quantityPointer, int arraySize, ifstream &inFile);
void sortData(int *numbersPointer, double *pricesPointer, int *quantityPointer,int arraySize);
void printData(int *numbersPointer, double *pricesPointer, int *quantityPointer, int arraySize);
int searchData(int *numbersPointer, int searchValue, const int arraySize);
void searchLoop(int *numbersPointer, double *pricesPointer, int *quantityPointer, int arraySize);

/*
 * Main
 */
int main() {
    //declare variables
    int arraySize = 0;
    int *sizePointer;//pointer for array size
    int *numbersPointer;//pointer to item numbers
    double *pricesPointer;//pointer to item prices
    int *quantityPointer; //pointer to item quantity
    int itemNumbers[arraySize]; //holds the item numbers
    double itemPrices[arraySize]; //holds the item prices
    int itemQuantity[arraySize]; //holds the item quantity

    //Welcome message to user
    intro();

    //point to arrays size
    sizePointer = &arraySize;
    //point to item array
    numbersPointer = itemNumbers;
    //point to price array
    pricesPointer = itemPrices;
    //point to quantity array
    quantityPointer = itemQuantity;


    //open the file
    ifstream inFile;
    inFile.open("inventoryData.txt");

    if (!inFile)
    {
        cout << "********** An Error has occurred!! **********" << endl << endl;
        cout << "The data text file was not in the correct directory or does not exist." << endl <<
                "Find the file and place it in the same directory and restart the program." << endl << endl <<
                "The program will now terminate." << endl;
        exit(0);
    }

    //get file input
    getArraySize(sizePointer,inFile);

    //read in the data from the file
    readData(numbersPointer, pricesPointer, quantityPointer, arraySize, inFile);

    //sort the data
    sortData(numbersPointer, pricesPointer, quantityPointer, arraySize);

    //print the data in table format
    printData(numbersPointer, pricesPointer, quantityPointer, arraySize);

    //search for an item number and display its cost and quantity
    searchLoop(numbersPointer, pricesPointer, quantityPointer, arraySize);

    return 0;
}

/*
 * Function: intro
 * Description: Displays an intro message to the user
 */
void intro() {
    //Program introduction
    // \n and endl wanted to practice with both.
    cout << "*****************************************" << endl
            << "** Welcome to Program 1                ** \n"
            << "** Created by: Brandon                 ** \n"
            << "** Sorting and Searching Arrays        **" << endl
            << "*****************************************" << endl << endl;
}
void getArraySize(int *sizePointer, ifstream &inFile){
     inFile >> *sizePointer;

    if (*sizePointer <= 0) // verifying that the file contains atleast one account number
    {
        cout << "The file does not contain any data." << endl;
        cout << "The program will now terminate." << endl << endl;
        *sizePointer = NULL;
        exit(0);
    }
    else{
            cout << "The file contains " << *sizePointer << " account number(s)." << endl << endl;
    } 
}


/*
 * Function: readData
 * Description: Retrieves 10 item numbers, their price and quantity
 * from the user and stores their answers in 3 parallel arrays.
 */
void readData(int *numbersPointer, double *pricesPointer, int *quantityPointer, int arraySize, ifstream &inFile) {

    for (int inCount = 0; inCount < arraySize; inCount++)
    {
        inFile >> *(numbersPointer + inCount);
        inFile >> *(pricesPointer + inCount);
        inFile >> *(quantityPointer + inCount);
    }
}

/*
 * Function: sortData
 * Description: Sorts 3 arrays in parallel, in ascending order.
 */
void sortData(int *numbersPointer, double *pricesPointer, int *quantityPointer, int arraySize) {

    //variables
    int numbersTemp, quantityTemp;
    double pricesTemp;
    bool swap;

    do {
        swap = false;
        for (int count = 0; count < arraySize - 1; count++) {
            if (numbersPointer[count] > numbersPointer[count + 1]) {
                numbersTemp = numbersPointer[count];
                quantityTemp = quantityPointer[count];
                pricesTemp = pricesPointer[count];

                numbersPointer[count] = numbersPointer[count + 1];
                pricesPointer[count] = pricesPointer[count + 1];
                quantityPointer[count] = quantityPointer[count + 1];

                numbersPointer[count + 1] = numbersTemp;
                pricesPointer[count + 1] = pricesTemp;
                quantityPointer[count + 1] = quantityTemp;

                swap = true;
            }
        }
    } while (swap);
}

/*
 * Function: printData
 * Description: prints the values of 3 arrays in table format
 */
void printData(int *numbersPointer, double *pricesPointer, int *quantityPointer, int arraySize) {

    //set the header for the table
    cout << "|" << setw(20) << "Item Numbers" << setw(5) << "|" << setw(17)
            << "Item Prices" << setw(6) << "|" << setw(20) << "Item Quantity" << setw(4) << "|" << endl
            << "=========================================================================" << endl;
    //print the data from the arrays
    for (int count = 0; count < arraySize; count++) {
        cout << "|" << setw(13) << numbersPointer[count]
                << setw(12) << "|" << setw(13) << fixed << setprecision(2) << pricesPointer[count]
                << setw(10) << "|" << setw(13) << quantityPointer[count] << setw(11) << "|" << endl
                //end of each row include a line
                << "-------------------------------------------------------------------------" << endl;
    }
}

/*
 * Function: searchData
 * Description: Search data is a binary search that accepts and array
 * and a search value, it then searches the array with the search value
 * and returns the values position in the array  or  -1 if its not in the array
 */
int searchData(int *numbersPointer, int searchValue, const int arraySize) {

    int low = 0;
    int high = arraySize - 1;
    int mid;

    while (low <= high) {
        mid = (low + high) / 2;

        if (searchValue == numbersPointer[mid]) {
            return mid;
        } else if (searchValue > numbersPointer[mid]) {
            low = mid + 1;
        } else {
            high = mid - 1;
        }
    }

    return -1;
}

/*
 * Function: searchLoop
 * Description: Asks the user to search for a number or exit(loop)
 * when a number is inputed it will call the searchData() function
 * and will print out the results for that search.
 */
void searchLoop(int *numbersPointer, double *pricesPointer, int *quantityPointer, int arraySize) {

    // Declare variables
    int result = 0; //holds search result
    int searchValue = 0; //holds search input from user

    //search for an item number and display its cost and quantity
    do {

        //start on a new line
        cout << endl << endl;
        cout << "Enter an item number to search or negative number to exit: ";
        cin >> searchValue;

        //if searchValue is less than 0 quit loop
        if(searchValue < 0){
            break;
        }

        //search for the item number the user entered   
        result = searchData(numbersPointer, searchValue, arraySize);


        //check to see if the search returned a result.
        if (result == -1) {

            //Search did not return any results
            cout << "\n No results found..." << endl;

        } else if (result >= 0) //returned a result
        {

            cout << "Search results for item number " << searchValue << " :" << endl << endl;

            //set the header for the table
            cout << "|" << setw(17) << "Item Prices" << setw(6) << "|"
                    << setw(20) << "Item Quantity" << setw(4) << "|" << endl
                    << "================================================" << endl;

            //output the price and quantity
            cout << "|" << setw(13) << fixed << setprecision(2) << pricesPointer[result]
                    << setw(10) << "|" << setw(13) << quantityPointer[result]
                    << setw(11) << "|" << endl

                    //end of each row include a line
                    << "------------------------------------------------" << endl;

        }

    } while (searchValue >= 0);

}

That is not what your teacher wants you to do. They do not want you to create pointers to already created arrays.. Btw, avoid creating an array of size 0.

Your teacher wants:

  1. You to read the first line of the file into an integer "ItemCount".
    This integer will hold the amount of lines/items to read.

  2. You must then create arrays of "ItemCount" in size.
    So if the first line of the file is 3, you must create an array of size 3.
    If the first line of the file is 4, you must create arrays of size 4.

This can be done like so:

void ReadFile(int &ItemCount, int* &ItemNumbers, double* &Prices, int* &Quantities)
{
    std::fstream File("inventoryData.txt", std::ios::in); //Setup the stream to read the file.

    if (File.is_open()) //If we can open the file, lets start reading it.
    {
        File >> LinesRead;  //Read the first line of the file. Store it in "ItemCount" variable.

        ItemNumbers = new int[ItemCount]; //Allocate space to hold "3" integers aka "ItemCount" amount.
        Prices = new double[ItemCount]; //Same thing.. we need space for 3 prices.
        Quantities = new int[ItemCount]; //And 3 quantities..

        for (int i = 0; i < ItemCount; ++i)  //Lets read "3" lines/items.. Remember "ItemCount" is the first line of the file. Aka "3".
        {
            File >> ItemNumbers[i]; //Read item number first. Just like std::cin >> ItemNumbers[i];
            File >> Prices[i];      //Read prices next.
            File >> Quantities[i];  //Read quantities after.
        }

        File.close(); //Close it when finished.
    }
}

int main()
{
    int ItemCount = 0; //Integer.. Not a pointer. We don't need an array.

    int* ItemNumbers = NULL;  //We need an array of item numbers.
    double* Prices = NULL;    //We need an array of prices.
    int* Quantities = NULL;   //We need an array of quantities.

    ReadFile(ItemCount, ItemNumbers, Prices, Quantities); //Read our file into our pointers..


    //Do whatever you want with Item information now.. They are in the pointer arrays..
    //Sort them, etc..


    //Since ReadFile uses "new .. []" to allocate memory for our pointer arrays, we must delete[] it when finished..

    delete[] ItemNumbers;
    delete[] Prices;
    delete[] Quantities;

    return 0;
}

Thank you for your helping understand this!! I owe you one!

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.