5 positive numbers

I am required to write a code for getting 5 positive numebrs from the user.
Here is my code:

cout << "Write 5 positive numbers:" << endl;
int input;
int num[5];

for(int i = 0; i <= 4; ++i){
cin >> input;
if(input < 0){
cout << "Error" << endl;
}else{
num[i] = input;
}
}
for(int i = 0; i <= 4; ++i){
cout << "Number " << i << " = " << num[i] << endl;
}

The problem is that array should store only positive numbers. When I enter negative num, it stores it too and then prints the garbage value. For example inputs are: 3 -2 1 6 8
The output is:
Number 0 = 3
Number 1 = -1608404014
Number 2 = 1
Number 3 = 6
Number 4 = 8

The array should ask the user enter the input until all 5 buckets in array will be filled only by positive numbers
enter the input until all 5 buckets
until

While there are less than 5 buckets full ...
You need 2 loops. The outer one reads 5 numbers. The inner one reads a single number until it's positive.
One simple way to do it:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
#include <iostream>

using std::cout;
using std::cin;

int main()
{
  int input, num_entered = 0;

  int num[5] = {0};

  cout << "Enter 5 positive numbers:" << '\n';

  while (num_entered < 5)
  {
    cin >> input;
    if (input > 0)
    {
      num[num_entered] = input;
      num_entered++;
    }
    else
    {
      cout << "Invalid input\n";
    }
  }
  for (int i = 0; i < 5; ++i) 
  {
    cout << "Number " << i << " = " << num[i] << '\n';
  }

  system("pause");
  return 0;
}


OUTPUT

Enter 5 positive numbers:
1
-2
Invalid input
3
4
-5
Invalid input
6
7
Number 0 = 1
Number 1 = 3
Number 2 = 4
Number 3 = 6
Number 4 = 7
closed account (48T7M4Gy)
A mite dodgy but one's enough:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
#include <iostream>

using namespace std;

int main()
{
    cout << "Write 5 positive numbers:" << endl;
    
    int input = 0;
    int num[5] = {0};
    
    for(int i = 0; i <= 4; ++i)
    {
        cin >> input;
        if(input < 0)
        {
            cout << "Error" << endl;
            i--;
        }
        else
        {
            num[i] = input;
        }
    }
    
    for(int i = 0; i < 5; ++i)
    {
        cout << "Number " << i << " = " << num[i] << endl;
    }
    return 0;
}
Topic archived. No new replies allowed.