I wrote this short console program for my introductory C++ class, and technically it functions properly and I have met all the criteria. However, I dislike that the console window closes after a failed input, and would like to learn how I could refactor this program so that failed input instead prompts for new, correct input, continuing from where the user left off. I feel like maybe there's a way to do this with an array and a do...while
loop, but my experiments have failed. I apologize if I'm not being very clear, I'm a total beginner.
#include <iostream>
using namespace std;
float first;
float second;
float third;
float fourth;
float fifth;
float total;
int main(){
// Promt the user to enter 5 decimal values
cout << "Enter 5 decimal values: ";
cin >> first >> second >> third >> fourth >> fifth;
// Clear and discard input errors
if (cin.fail()) {
cout << "Invalid entry; Please enter numbers only." << endl;
cin.clear();
cin.ignore(10000, '\n');
}
else {
// Add the values together
total = first + second + third + fourth + fifth;
// Convert to the nearest integer and print the result
cout << fixed << setprecision(0) << "The total is: " << total << endl;
}
system("pause");
return 0;
}
By the way, I'm aware that using std
is considered bad practice; however, it is part of the requirements for the assignment, so I left it in.