ValKi
ValKi

Reputation: 13

How to make array

I want to create n number element in an array. In the first input line I ask to give the number of elements, in the second line I ask for the actuall elements. I tried this code

int main() {
    int first_line;
    cin >> first_line;
    int second[first_line];
    cin>>second;
    cout<< second;


    return 0;
}

Input should look like

input
       8
       1 2 3 4 5 6 7 8
output
       1 2 3 4 5 6 7 8

I need to the second line be in integer array.

Upvotes: 0

Views: 103

Answers (3)

Richard Chambers
Richard Chambers

Reputation: 17643

There are several collection types available in the C++ Standard Template Library, one of which std::vector<> will work just fine.

However if you want to use an array with straightforward array mechanics and syntax then an alternative would be to create your own array as in:

#include <iostream>
#include <memory>

int main() {
    int first_line;
    std::cin >> first_line;

    int *second = new int[first_line];    // create an array, must manage pointer ourselves

    // read in the element values
    for (int i = 0; i < first_line; i++)
        std::cin >> second[i];

    // write out the element values with spaces as separators
    for (int i = 0; i < first_line; i++)
        std::cout << second[i] << "  ";

    delete [] second;    // delete the array as no longer needed.
    return 0;
}

Using std::unique_ptr<> to contain the pointer to the array would be more convenient and safer and just as easy to use. Create the array with std::unique_ptr<int[]> second( new int[first_line]); and then remove the no longer needed delete[]. std::unique_ptr[] will take care of deleting the array once it goes out of scope.

Upvotes: 0

Jerry Coffin
Jerry Coffin

Reputation: 490653

An array (at least as it's defined in C++) simply can't do what you're asking for.

What you're really looking for is a std::vector, which does this quite nicely.

int main() {
    int first_line;
    cin >> first_line;
    std::vector<int> second(first_line);

    for (int i=0; i<first_line; i++) {
        int temp;
        cin>>temp;
        second.push_back(temp);
    }

    for (auto i : second) {
        cout<< i << ' ';
    }
    cout << "\n";

    return 0;
}

Upvotes: 1

Oblivion
Oblivion

Reputation: 7374

First thing first you cannot use a variable length array in C++. So use a std::vector instead.

std::vector<int> second(first_line);

for reading you need to cin in a loop e.g. for loop.

The implementation left to the OP as a practice.

Upvotes: 0

Related Questions