do while loop problems

In the code below I have 3 loops, all with if and else statements in them. The purpose of having these loops is to ensure the user types a valid integer in. While trying to increase redundancy, I tried putting a character in for one of my three int values. The result is the program endlessly loops.

The solution I’m looking for is this. I want to keep Assignement1, Assignment2, and Test1 all integers. I also want to keep the program from endlessly looping when you input a letter rather than a number.

Is this possible?

Thanks for the time.

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
56
57
58
59
void storeValues()
{
	string eatEnter;
	string aNumber;
	string Name;
	int Assign1;
	int Assign2;
	int Test1;
	double finalGrade;

	cout << "Enter A-Number:";
	getline(cin, aNumber);
	cout << "Enter Name:";
	getline(cin, Name);
	do
	{
	cout << "Enter Assignment 1 Score (Possible 15):";
	cin >> Assign1;
		if (Assign1 >= 0 && Assign1 <= 15)
		{
			break;
		}
		{
			cout << "Value needs to be between 0 and 15." << endl;

		}
	}while(1);
	do
	{
	cout << "Enter Assignment 2 Score (Possible 35):";
	cin >> Assign2;
	if (Assign2 >= 0 && Assign2 <= 35)
		{
			break;
		}
	else
		{
			cout << "Value needs to be between 0 and 35." << endl;
		}
	}while(1);
	do
	{
	cout << "Enter Test 1 Score (Possible 50):";
	cin >> Test1;
	if (Test1 >= 0 && Test1 <= 50)
	{
		break;
	}
	else
		{
			cout << "Value needs to be between 0 and 50." << endl;
		}
	}while(1);
	getline(cin,eatEnter);

	finalGrade = (Assign1 + Assign2 + Test1);
	s_count++;
	students[s_count].studentInfo(aNumber, Name, Assign1, Assign2, Test1, finalGrade);
}

the while() portion needs to have a test in it, the way that you run it now is saying that while("true") and there's no way to end the loop. Try watching this guy's tutorial on do while loops; http://www.youtube.com/watch?v=yRdPe2acogw , you may want to use plain old while loops instead.
@newbieg,

there is no need any condiition in the while because the loop is exited by the condition inside the loop. Look at the body of the loop

1
2
3
4
5
6
7
8
9
10
11
12
13
do
	{
	cout << "Enter Test 1 Score (Possible 50):";
	cin >> Test1;
	if (Test1 >= 0 && Test1 <= 50)
	{
		break;
	}
	else
		{
			cout << "Value needs to be between 0 and 50." << endl;
		}
	}while(1);


It seems that loops work correctly. So the problem is somewhere else.

@JRimmer,

if you want that there will not be endless loop when a letter is entered you shall check the state of the input stream after each input.
Last edited on
Topic archived. No new replies allowed.