How to stop cin into an array by entering 0?

I'm trying to use cin to read numbers into an array up to size 100. The program will know that the user is done inputting numbers when a zero is entered. This is what I have so far:
1
2
3
4
5
6
7
8
9
10
11
12
  const int size = 100;
  int Array[size];
  for (int i=0; i<size; i++){
      cin >> Array[i];
      //THIS IS WHERE THINGS GO WRONG
      if (Array[i]=0){
         break;
      }
  //code to print array
  for (int n=0; n<size; n++){
      cout << Array[n];
  }

Thanks for any help you can give me! I'm confused at how to use an array without a predefined length. I feel like there is a simple solution to this but I cannot get it to work.
You used a single '=' not a '==' for line 6, but this is what I would do:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
#include <iostream>

using namespace std;

const int SIZE = 100;

int main()
{
  int count = 0;
  int Array[SIZE];

  for (int i = 0; i < SIZE; i++)
  {
	  count += 1; //or you can do count++; or count = i;
	  cout << "Enter array for position " << i << ": ";

      cin >> Array[i];
    
      if (Array[i] == 0)
           break;
   }

  //code to print array
  for (int n = 0; n < count; n++)
  {
      cout << Array[n] << endl;
  }

  return 0;
}


I added a variable count to keep track of how many numbers are entered, otherwise when you print out 100 values from the array everything that isn't a value you entered will just be garbage data.

Hope that helps somewhat! :)

P.S. If you don't want to have a const predefined array size you should use a dynamic array using a pointer.
Last edited on
Thanks! Worked beautifully! One more quick question, how would I go about removing the trailing zero from the array?
Do you mean re-size the array? If that's what you mean, you should think about either going the dynamic route, or you could use a vector instead, which you can have grow on the fly as you receive the numbers.
Topic archived. No new replies allowed.