Search code examples
c++arraysc++14dynamic-memory-allocation

How to dynamically input array in c++?


This is a simple code where I want to print the elements of an array which are provided as input.

int main() {
    int t;
    cin>>t;
    while(t--){
        int n;
        cin>>n;

        int *arr = new int[n];
        for(int i=0;i<n;i++)
            cin>>arr[i];

        for(int i=0;i<n;i++)
            cout<<arr[i];
        cout<<endl;
    }
    //code
    return 0;
}

input:

2
5
1 2 3 5
10
1 2 3 4 5 6 7 8 10

ouput poduced by this code

123510
2

but this shouldn't be the output as it should produce the other array from 1-10.

There must be a silly mistake but i don't know where


Solution

  • Your third line of input is missing a 4.

    It's thus parsed as:

    2  // two arrays
    5  // first one size 5
    1 2 3 5
    10  // end of the first array
    1  /* second one size 1 */ 2 /* end of the second array */ 3 4 5 6 7 8 10 
    // the end is ignored