I am new here and this is my first post. I have a question that I can't find on google. I'd be grateful if you could help me. I have written many programs dealing with arrays and wanted to know how can I validate an input. Say I have the following code:

QUESTION: how can I make it so that the user can only input numbers from 5-15 in the array? Thank you so mucu

#include <iostream.h> 

int main() { int anArray[5]; int i;

cout <<"Enter 5 numbers to fill the array."; for(i = 0; i < 5; i++) { cout << “anArray[“ << i << “]” << “n”; cin >> anArray[i]; }

for(i = 0; i < 5; i++) { cout <<"Here are the numbers in the array. cout <<"anArray[" << i << "]" << anArray[i] << "n";

} return 0;

8 Years
Discussion Span
Last Post by firstPerson

Here is one way of doing it.

int Array[5] = {0};
	int num(0); //the number the use will input;

	for(int i = 0; i < 5; i++)
		cout<<"Enter value# "<<i<<":  ";
		cin >> num;
		if( num >=5 && num <= 15) //put number into array only if its within bounds
			Array[i] = num;
			cout<<"Number should be from 5 to 15. Try again\n";
			i = i - 1; //if not subtract 1 from i to reset it

THANK YOU SO SO MUCH firstPerson. Now I can adda data validation to all my older programs! Thank you so much.

This question has already been answered. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.