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
#include <iostream>
usingnamespace 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;
}
#include <iostream>
usingnamespace 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:
#include <iostream>
usingnamespace 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;
}