I'm new into programming and today I'm here because I need help with a program that I'm writing. This program is an exercise from the book : Programming principles and practice using C++. I have to write a program that uses a function to find the min, max, mean and median element in a vector
of doubles. I tried to wrote this loop but I'm having some problems with reading numbers. Here is the loop :
void reading_loop()
{
cout << "Enter a series of numbers ending with any non-digit character : ";
while (true) try {
vector<double> values;
double x;
while (cin >> x) values.push_back(x);
Stats result = get_stats(values); // a stats holds the results
print_vector(values);
print_stats(result);
cout << "Try again : ";
}
catch (runtime_error& e) {
cerr << "Error : " << e.what() << '\n';
}
catch (...) {
cerr << "Oops, something went wrong somewhere \n";
}
}
The object called result of type Stats
is a simple struct that the author told me to use to hold the results from get_stats(values)
. Basically the problem with this program is in the while(cin >> x)
loop, when I execute the program and I enter the first series of numbers and stop reading using the character : ' ; ' the program prints the corrects results as it should, but then It skips reading with while(cin >> x)
bringing the program into an infinite loop. I read about question like this on the forum but I am new to programming so I don't know of functions such as cin.ignore()
or cin.clear()
. How would you solve this problem ?