I've been trying to find a way to get user input from keyboard for an array. The user can enter up to 100 elements. If at any point the user wishes to stop, they enter 0 and the array will not take anymore inputs. When I run the code below and enter 0 it still goes through the while loop. I don't know what I am doing wrong. Looking for help with this problem!!
#include <iostream>
#include <iomanip>
using namespace std;
#define i 10
void getElements(int array[]);
int main()
{
int array[i];
getElements(array);
cout << array;
return 0;
}
void getElements(int array[])
{
cout << "Please enter up to " << i
<< " positive nonzero integer elements. Enter 0 to stop input.\n" << endl;
for(int count = 0; count < i; count++)
{
cout << "array[" << count << "]: ";
cin >> array[count];
while((!array[count]) || (array[count] < 0))
{
cin.clear();
cin.ignore(10000, '\n');
cout << "Sorry, invalid input. Was expecting a positive integer."
<< " Please try again." << endl;
cout << "array[" << count << "]: ";
cin >> array[count];
}
if (array[count] == 0)
{
// code to stop input from keyboard.
cout << "stop input" << endl;
}
}
}
#definein C++, useconstwith an appropriate type and value. Additionally reservingiis really inconvenient if not downright rude, that's expected to be free for use as an iterator variable. This would be better expressed asconst int max_number = 10.std::vector<int>andpush_back. Don't use C arrays if you can help it.ifstatement, instead ofwhile, and abreak. (3) Think more about thewhilecondition.