Code completely ignoring my if statements

My aim with this program is for votes to only be recorded if the value is any number from 0 to 4 and to continually loop until a negative number is input. The problem that's been occurring is that the program quits after the first input. It completely skips past the do while loop even if the number that is input is greater than -1.

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
43
44
45
46
47
48
49
50
51
52
53
54
55
  int main()

{

	//Declarations
	int average = 0;
	int votes = 0;
	int rating = 0;
	int sumTotal = 0;


	//detailLoop()
	do {
		//housekeeping()
		cout << "Input a rating from 0 to 4 (input a negative number to quit)" << endl;
		cin >> rating;
		if (rating > -1 && rating < 5); {
			//average()
			sumTotal = sumTotal + rating;
			votes = votes + 1;
			average = sumTotal / votes;
			break;
		}
		if (rating <= -1); {
			cout << "The program will now quit" << endl;
			break;
		}
		if (rating >= 5); {
			cout << "This value is outside the accepted range and will thus not be recorded" << endl;
			break;
		}
		while (rating > -1);
	}






	//finishUp()
	while (votes >= 1); {
		cout << "This movie has an average score of " << average << " out of 4 after receiving " << votes << " votes" << endl;
		
		
	}
	if (votes == 0); {
		cout << "The program has been quit without any ratings" << endl;
		
		
	}


	return 0;
	
}
Be aware that, for a "while" loop, you need either:
while(condition) { statement1; statemen2; ...; staementN; }
...or:
do { statement1; statemen2; ...; staementN; } while(condition);

So, in the code you have posted, you actually have:
1
2
3
4
5
do {                   //line #13
    //housekeeping()
    [...]
}
while (votes >= 1);    //line #41 


The many linebreaks you put before the while() in line #41 are irrelevant for the C compiler ;-)

The code in line #42 and line #47 is executed unconditionally.


Furthermore, this code in line #32 is a "while" loop which does absolutely nothing in its body:
while (rating > -1);

(...but still checks the condition, so potentially hangs in an infinite loop)


For an "if" statement you need:
if(condition) { statement1; statemen2; ...; staementN; }

Note: There must not be a semicolon immediately after the "if" condition, because otherwise the code translates to "if condition then nothing", and the code in curly braces is executed unconditionally ;-)


I much recommend you increase the warning level of your C compiler to the maximum, because most of the problems in your code should have triggered a warning. If there are any warnings, do not ignore them!
Last edited on
Topic archived. No new replies allowed.