Do/while loop works with vectors??

Hi everyone,

I started with a code to calculate the final grade of the students asking for input information, such as midterm, final, homework, presentations and more grades. That piece of code works but exits after sending the final grade for one student and I'd like the programme to ask if the user wishes to input data for another student, so I tried to implement the do-while loop but the programme prints the last question and exits.

I am posting here a shorter and simpler version. I tried with a factorial calculator and the do-while loop does the work, but for the code below doesn't work. If I comment part of the code and change variables for constant data, the question appears and I have the option to select yes or no, but the whole code doesn't allow me to reply to the question.

Do I need a specific library for this action, particularly working with vectors?

Thanks for your time and comments.

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
#include <iostream>
#include <vector>
using namespace std;

int main(){
	char indicator = 'n';
	do {
		double x = 0, suma = 0, final = 0;
		vector<double> homework;
		typedef vector<double>::size_type vec_sz;

		homework.clear();
		cout << "Enter your grades: ";
		while(cin>>x){
			homework.push_back(x);
			suma += x;
			};

		vec_sz size = homework.size();
		final = suma/size;
		cout << "Final grade is: " << final;

		cout << "\nAnother count? (y or n) " << endl;
		cin >> indicator;
		} while((indicator == 'y') || (indicator == 'Y'));
		
	system("pause");
}
1
2
3
4
5
6
while(cin>>x){
  //...
}
//We are here because the reading failed
//that means that `cin' is in an invalid state
cin >> indicator; //so this will fail 
¿how are you terminating the loop inline 14?
Hi ne555,

Thanks for replying.

Yes, I didn't explain that :P I am simply typing end-of-file command (ctrl+z). I don't specify it in this code 'cos it is only me trying to make this piece of code work, specifically for the do-while loop.

In another file I have a longer code where I include a flag to indicate the end of input. Is this causing the conflict??
When you reach the end-of-file the stream becomes invalid, you simply need to restore it.
So put cin.clear(); after the loop. If still doesn't work, discard what you have in the input buffer cin.ignore();
I see; with cin.clear() it worked. Thanks a lot ne555.
Topic archived. No new replies allowed.