do while loop won't stop for input

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?

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
35
36
37
38
39
40
41
42
  
#include <iostream>
#include <iomanip>

using namespace std;

const int 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)
	{
	case true:    

		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);

	case false:

		//operations on the variable 'num'.....

	return 0;
}
Last edited on
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: ";
}
Last edited on
Topic archived. No new replies allowed.