Restricting user input for arrays

So, I want to use arrays to store my user's array, but I don't want the user to input a negative number or a number greater than 1000. How would I do this -- I'm stumped. I was thinking of using a do while loop

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
int main()
{

    float array[7];

    for (int x = 0; x<7 ; x++)
    {

    cin >> array[x];  
    }

// i used another for loop because I wanted to echo the array in 1 line
    for (int z = 0; z<7; z++) 
    {
        cout << array[z] << "\t";
    }


if I were to try using a do while loop

1
2
3
4
5
6
7
    for (int x = 0; x<7 ; x++)
    {
    do
    {
    cin >> array[x]; 
    }while(array[x] <= 1000 && array[x] > 0);
  


doing this would give me funky numbers whiles still letting number greater than 1000 to go through
Last edited on
1
2
3
4
5
6
7
8
9
for (int x = 0; x < 7; x++) {
    float temp;
    
    for(std::cin >> temp; temp < 0 || temp > 1000; std::cin >> temp) {
        std::cout << "Invalid number entered!\n";
    }

    array[x] = temp;
}
numbers := 0
WHILE numbers < 7 AND read value
  IF number is valid
    array[numbers] := value
    increment numbers
Last edited on
Thanks you guys. Major brain fart on my part.

Smac89, could you explain to me why you used || instead of &&? || doesn't check the second condition if the first one is true. Please correct me if I'm wrong. Never mind. I'm stupid.

And keskiverto, what does the single colon mean? It's still a bit confusing for me after I read the section about it (the one on this website).
Last edited on
Smac89, could you explain to me why you used || instead of &&?


Because temp cannot less than 0 AND greater than 1000 at the same time. Such a statement would never be true. Thus, || is what you need.
Leave the first for-loop as it is and put an if-statement with your condition in the second loop before you cout the array, like below.

1
2
3
 for(int n=0; n<7; n++)
        if(array[n]>0 && array[n]<1000)
        cout << array[n] << endl;
Last edited on
Yeah, I just got it before I check this thread again. I just read the code wrong -- It makes perfect sense now. Thanks for the help/explaination Arslan7041.
Last edited on
No problem.

You can combine what I did with what Smac89 posted. This will let the user know (through an output message on-screen) that their input is not acceptable, as well as only output the "accepted" numbers.
Topic archived. No new replies allowed.