I'm trying to do input validation with this array. I do not want the user to enter a negative number. However, with the way I wrote it, it will compile and when user enters a negative number it will give a debug error. and still count the negative number. What is a better way to do the input validation.
#include <iostream>
usingnamespace std;
int main()
{
int numbers[6];
int smallest = 0, largest = 0;
int temp = 0;
for (int i = 0; i < 6; i++)
{
cout << "Enter number" << i + 1 << ":" << endl;
cin >> numbers[i];
if (numbers[i] < 0) //input validation does not work as intend
{
cout << "Enter only positve numbers. \n";
cin >> numbers[6];
}
}
smallest = numbers[0];
largest = numbers[0];
for (int i = 1; i < 6; i++)
{
temp = numbers[i];
if (temp < smallest)
{
smallest = temp;
}
if (temp > largest)
{
largest = temp;
}
}
cout << "Largest number is: " << largest << endl;
cout << "Smallest number is: " << smallest << endl;
return 0;
}