Do while loop - only works on 2nd try

I am practicing a nested do while loop for a program that asks the user to input a number and that number of "stars" will appear. However, the error message appears even if a valid number is used. In fact, it seems that no matter what the first number is inputted, it will say it is invalid. Then, the second number will be done correctly. Please help

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
#include <iostream>
using namespace std;
 
int main ()
{

int num1;
   
cout << "Please enter the number of stars to display: ";
cin >> num1;
  if (num1 < 0)
  cout << "Oops! I can't display a negative number of stars! \n";
   do { cout << "Please enter a valid number. \n"; 
   cin >> num1;	
      do										
      {
      cout << "*";					
      num1--;							
      }while(num1 > 0);				
  } while(num1 < 0);
  cout << endl;  
system("pause");
return 0;
}
After trying different solutions, i came up with this:

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
#include <iostream>
using namespace std;
 
int main ()
{
   int num1;
   
	
		cout << "Please enter the number of stars to display: ";
		cin >> num1;	
		if (num1 < 0){
		
		do {cout << "Oops! I can't display a negative number of stars! \n"
		<< "Please enter a valid number. \n"
		<< endl;  
		cin >> num1; }
		while (num1 < 0);
		

		}
		else (num1 > 0);				
		 do{
	 	 cout << "*";
 		 num1--;	
		 }while(num1 > 0);
		 cout << endl;
		
   system("pause");
   return 0;
}




This fixed the problem I had. Please reply if there is an easier/better solution. I'm a beginner still and would appreciate any advice.
are you sure your code worked? you have some errors at line 21 else (num1 > 0);, what are you trying to do with this line. And also you didn't #include <cstdlib> so how can you use system(). And also i recomend using cin.get() instead of system ("PAUSE"); and lastly indent properly:

your code is just right but i just wanted to show my version:
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
#include <iostream>

using namespace std;
 
int main ()
{
	int num1;
   
	cout << "Please enter the number of stars to display: ";
	cin >> num1;	
	
	while ( num1 <= 0 ) {
			cout << "Oops! I can't display zero or negative number of stars! \n" 
                                << "Please enter a valid number. \n" << endl;
			cin >> num1;
	}
	
	do {
		cout << "*";
		num1--;	
	} while (num1 > 0);
		
	cout << endl;
		
	cin.get();
	
	return 0;
}
The first program differs logically from the other two. It attempts to do:
Repeat the following:
1. Get a valid number
2. Show stars.

The others do print only one line; no repeat. There is no nesting of loops.

When you do the repeating version, the input can be one of three:
1. Valid number to show
2. Signal to end the loop
3. Neither of those.

How to react to each possibility is a design decision.
Topic archived. No new replies allowed.