Array help!

Hey! so this is a part of ym assignment :
The user will be prompted for the three fields: productID, price, quantity on hand. Then the information may be added to the first empty location in the array.

I need help with find the first empty space in the array and setting it to the number entered in and also setting a string and int array to have all the same values in all positions.
string num;
string product[1000];
int i;
cout << "Enter Product ID: " ;
getline(cin,num);
for (i=0; i<=SIZE; i++){
if(product[i] ="")
product[i]=num;
So this is what i'm guessing you need parallel arrays one for string and one for int. So you should have something like
1
2
3
4
5
6
7
8
9
10
11
12
    const int size = 1000;
    int numArray[size];
    string product[size];
    int num;
    string productName;
    for(int i = 0; i < size; i++){
        cin >> num;
        cin.ignore(); // Ignore new line when cin is combined with getline()
        getline(cin, productName);
        numArray[i] = num; // Places number at index i
        product[i] = productName; // Places product at index i
    }
Last edited on
Thanks but i have to assume the array is already filled with some product ids and I have to find the next available position in the array! Do you know how I would be able to do it
How are you placing the product ID inside the array? Assuming product ID aren't 0, you can use check with if statement if(numArray[i] != 0){ // do something }
productID, price, quantity on hand
I think you need a struct, something like:
1
2
3
4
5
struct MyField {
    int productID;
    double price, 
           quantity;
};


the first empty location in the array
Are you required to stick to C-style arrays?
Are you guaranteed empty locations are initialized to 0?
I’m having the user enter product IDs with cin and whenever they entered an Id I want the loop to go through each position until it finds a position that hasn’t been given a value through user input
And we have to stick with c style arrays, I never learned what a struct is. I don’t know how to intialize all locations in a string array to 0 or empty
To initialize your arrays:
1
2
3
4
const int NUM_ITEMS = 1000;
string productIDs[NUM_ITEMS]; // no need to initialize because all strings are "" 
double price[NUM_ITEMS] = {0}  // initializes all to 0 
int quantities[NUM_ITEMS] = {0}; // initializes all to 0 


To find the next index to insert you need to write a function that would return the index of the first non-default value in the array - like this:
1
2
3
4
5
int nextIndex(string[] productIDS)
{
  // TO DO return the index of the first string that is != "" or -1 if the array is full
  // use the global constant NUM_ITEMS for the size of the array.
}

Hope this makes some sense.

It did!! thanks :D
Topic archived. No new replies allowed.