This program is supposed to accept only positive integers. If a negative integer is entered, I want it to produce an error message and reprompt the user for input. (Only integers are expected as input. No further input error checking needed) I tried to do this with a do while loop, but after a negative integer is entered, the program continuously outputs the error message and prompt without accepting further input. I have tried a few different things including resetting the variable 'num' to a positive number at the beginning of the do block and clearing the buffer stream before reprompting for input. I also just tried changing the switch to an if statement. Same results. What is wrong?
#include <iostream>
#include <iomanip>
usingnamespace std;
constint SENTINEL = 0;
int main()
{
int num;
int numOriginal;
bool isDivisible;
cout << "\nThis program accepts a number as input and determines whether or\n"
<< "not it is divisible by 11. Input must be a POSITIVE integer.\n\n";
cout << "Enter a positive integer: ";
cin >> num;
switch (num < 0)
{
casetrue:
do
{
cout << "\n\nInvalid input. Number must be a positive integer. Try again\n\n";
cout << "Enter a positive integer: ";
cin >> num;
}
while (num < 0);
casefalse:
//operations on the variable 'num'.....
return 0;
}
Apart from the missing curly braces to end the switch statement (copy-paste problems), I will suggest putting a break statement after each case:
1 2 3 4 5 6 7 8 9 10
switch (/*some integer*/)
{
case 1:
/*execute some code*/
break; // break out of the switch statement
case 2:
/*execute some code*/
break; // break out of the switch statement
default:
}
or remove the switch statement in general and use a for-loop:
1 2 3 4 5
for ( cin >> num; num < 0; cin >> num )
{
cout << "\n\nInvalid input. Number must be a positive integer. Try again\n\n";
cout << "Enter a positive integer: ";
}