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
constint 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.
#include <iostream>
usingnamespace std;
constint 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.
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.