Storing multiple arrays based on user input

I'm trying to create a function where it allows the user to type in multiple amounts of integers, so if the user wanted to have 3 different storages that hold different integers, the input would look something like this:

1
2
3
4
5
6
    5 
    97 12 31 2 1 //let's say this is held in variable "a"
    1 3 284 3 8  // "b"
    2 3 482 3 4 // "c"
    2 3 4 2 3  // "d"
    99 0 2 3 42 // "e" 


Since we don't know what number the user will input every time, I'm not sure how to create a dynamically allocated array that will create an x amount of arrays every time.. I want to be able to access each index of a, b, c, d, e or however many arrays there are.

So far, this is what I have, but I'm having trouble creating the arrays since it's unpredictable. I'm purposely not using vectors because I don't really get how pointers work so I'm trying to play around with it.

1
2
3
4
5
6
7
8
9
10
    int* x;
    int length, numbers;
    cin >> length;
    x = new int[length]
  
    for (int i=0;i<length;i++)
    {
        cin >> numbers; //this doesn't work because it only grabs the first line for some     reason
        x[i] = numbers
    }


If anything seems unclear, please let me know! Thank you!
You are trying to put an array into an int. You are going to need an array of arrays.

You could do something like:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
int **x; //You should probably invest in a better name :P
int lines;
int numbers;

std::cout << "How many lines of numbers? ";
std::cin >> lines;

x = new int *[lines];

for( int i = 0; i < lines; ++i )
{
    std::cout << "How many numbers is this line? ";
    std::cin >> numbers;
    x[i] = new int[numbers];
    std::cout << "Please enter the numbers separated by spaces: ";
    for( int j = 0; j < numbers; ++j )
    {
         std::cin >> x[i][j];
    }
}

//
for( int i = 0; i < numbers lines; ++i )
    delete[] x[i];

delete[] x;


I would highly suggest you use a STL container such as a vector though.

*fixed error mentioned by SGH
Last edited on
Hm i tried this but it's not giving me the right output.

If i have

3
1 2 9
5 4 3

and i do
a[1][0] it gives me the value of 9 instead of 5? i'm not sure why.
Can you show the exact code you used?

http://ideone.com/4a8PuL
Last edited on
Topic archived. No new replies allowed.