Array Input

This is a discussion on Array Input within the C++ Programming forums, part of the General Programming Boards category; How would I fix this program so that the user is allowed to input any amount of numbers into the ...

  1. #1
    Registered User
    Join Date
    Jul 2010
    Posts
    13

    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!

    Code:
    #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
    Registered User whiteflags's Avatar
    Join Date
    Apr 2006
    Location
    United States
    Posts
    7,622
    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
    Posts
    7,317
    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, 12: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

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21