User Input for {x,y}

I want to change Item array[ ]={{x,y}}
How do I make Item arr[ ] into a user input?

1
2
3
4
5
    int W; //    Weight of knapsack
    cout << "Please Enter capacity of knapsack: " << endl;
    cin >> W;
    
    Item arr[] = { { 60, 10 }, { 100, 20 }, { 120, 30 } };


Thank you in advanced!
Last edited on
@againtry Hi,thank you for the link!but I want to change it to user input.
Hello lychee,

If you are asking:
1
2
3
4
5
int W; //    Weight of knapsack
cout << "Please Enter capacity of knapsack: " << endl;
cin >> W;

Item arr[W] = { { 60, 10 }, { 100, 20 }, { 120, 30 } };

Then No. C++ does not allow a VLA, (Variable Length Array). You could use "new" to create a dynamic array, but make sure that you use "delete" to free the memory when you are done with it.

Also avoid single letters for variable names. This may seem easy, but later they become hard to keep track of. A good name makes the code easier to follow. And save capital letters for variables defined as constants.

Andy
Hello lychee,

After rereading everything I think I understand better.

After entering the capacity of the knapsack you will need to ask the user for the "value" and "weight" of each item before you can change the values in the array.

It is not much, but this should give you an idea:

Please Enter capacity of knapsack: 100

 Enter the value of item (0 to end): 15
 Enter Weight of item: 10



I did take this a litter farther to deal with bad input:

Please Enter capacity of knapsack: a

     Invalid Input! Must be a number.

Please Enter capacity of knapsack: 100

 Enter the value of item (0 to end): a

     Invalid Input! Must be a number.

 Enter the value of item (0 to end): 15
 Enter Weight of item: a

     Invalid Input! Must be a number.

 Enter Weight of item: 10



And with a little work I get this:

 Please Enter capacity of knapsack: a

     Invalid Input! Must be a number!

Please Enter capacity of knapsack: 0

      Value must be greater than (0)!

Please Enter capacity of knapsack: 100

 Enter the value of item (-9 to end): a

     Invalid Input! Must be a number!

 Enter the value of item (-9 to end): 0

      Value must be greater than (0)!

 Enter the value of item (-9 to end): 15
 Enter Weight of item: a

     Invalid Input! Must be a number!

 Enter Weight of item: 0

       Value must be greater than (0)!

 Enter Weight of item: 10

 Enter the value of item (-9 to end): -9


 Press Enter to continue:


After all that "value" and "weight", (better names than 'x' and 'y'), now have something that you can put into the array.

Andy
Topic archived. No new replies allowed.