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;


Recommended Answers

All 3 Replies

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.

Your welcome. Now mark this thread solved.

[edit] Oh I see you have already done that:)

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.