Dismiss Notice
Join Physics Forums Today!
The friendliest, high quality science and math community on the planet! Everyone who loves science is here!

Need help in putting data into an array in c++

  1. Nov 29, 2011 #1
    Hi guys,
    I need to create an array in c++. But before I declare how many elements are in the array I want to prompt the user for input. I want to ask the user how many elements do they want in the array.
    What ever the user said, 5 or 20. I then want to enter these 5 values or 20 values myself.
    hope you can help.
  2. jcsd
  3. Nov 29, 2011 #2


    User Avatar
    Science Advisor
    Gold Member

    Do you know what the new operator is, and how to use it with an array?
  4. Dec 1, 2011 #3
    You may want to consider using the c++ structure "vector" rather than an array. A vector v (of double values in this example) of size N is created by
    Code (Text):

      // ... determine the value of N here ...

      // create a vector of N double values.
      std::vector<double> v(N);
    The usage is the same as for an array (except for extra options that you may find out some day).
  5. Dec 1, 2011 #4


    User Avatar

    Staff: Mentor

    I'm guessing this is a class assignment, so you need to use an array instead of a vector. But for future reference...

    Going further from Timo's example, you can declare the vector to have zero size initially, and then let it automatically expand as you add data to it. That way, you don't have to ask the user how many numbers he's going to enter.

    Code (Text):

    #include <iostream>
    #include <vector>

    using namespace std;

    int main ()
        vector<int> numbers;  // has length zero, initially

        cout << "Enter some numbers, terminating with control-D:" << endl;

        int n;
        while (cin >> n)
            numbers.push_back(n);  // append n to the vector and expand
                                   // the vector as necessary

        // the size() member function tells you how big the vector is

        cout << "You entered:" << endl;
        for (int k = 0; k < numbers.size(); ++k)
            cout << numbers[k] << endl;

        return 0;

    Code (Text):

    jtbell$ g++ vector_demo.cpp
    jtbell$ ./a.out
    Enter some numbers, terminating with control-D:
    [I][COLOR="Blue"](control-D entered here)[/COLOR][/I]
    You entered:
Share this great discussion with others via Reddit, Google+, Twitter, or Facebook