Thread: Array Input

  1. #1
    Registered User
    Join Date
    Jul 2010

    Question Array Input

    How would I fix this program so that the user is allowed to input any amount of numbers into the array? I'm absolutely confused.
    Thanks in advance!

    #include <iostream>
    using namespace std;
    int main()
          double numbers[num_elements] = {};
          int i;
          for (i = 0; i < num_elements; i++)
              cin >> numbers[i];
          system ("pause");
          return 0;

  2. #2
    Lurking whiteflags's Avatar
    Join Date
    Apr 2006
    United States
    If you haven't learned about vector yet, now is the time. Arrays by definition have a maximum capacity so there you have it.

  3. #3
    Registered User
    Join Date
    Jan 2005
    There are several options, and all are a little different than what you're trying to do in your example.
    1. Use a vector. The vector class is a standard library container that lets you add "any" amount of values to it. You could just keep pushing numbers on to the vector until the user stops or your machine runs out of memory.

    2. Make num_elements some big number and instead of allowing the user to input "any" amount of numbers, limit them to something less than that big number. For example, if you don't expect the user to ever enter more than 100 numbers, you could define num_elements as const in num_elements = 1000. Then just make sure they stop by the time they get to 1000.

    3. Use new[]/delete[] to make a dynamic array. This is similar to option one, but is not really recommended. I'd only do it if you're doing this for a class and you're not allowed to use vector or you're trying to learn how to manage memory with new[] and delete[].

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Checking array for string
    By Ayreon in forum C Programming
    Replies: 87
    Last Post: 03-09-2009, 03:25 PM
  2. Replies: 2
    Last Post: 07-11-2008, 07:39 AM
  3. Problem getting the input from a temp variable into the Array
    By hello_moto in forum C++ Programming
    Replies: 3
    Last Post: 03-16-2006, 01:50 AM
  4. Unknown Memory Leak in Init() Function
    By CodeHacker in forum Windows Programming
    Replies: 3
    Last Post: 07-09-2004, 09:54 AM