我为我的介绍性C++类编写了这个简短的控制台程序,技术上它的功能正常,并且符合所有条件。但是,我不喜欢在输入失败后关闭控制台窗口,并想了解如何重构此程序,以便失败的输入提示输入新的正确输入,并从用户停止的地方继续。我觉得也许有一种方法可以用一个数组和一个do...while
循环来做到这一点,但是我的实验失败了。我很抱歉,如果我不是很清楚,我是一个初学者。如何重构逻辑以获得更好的错误处理?
#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;
}
顺便说一下,我知道using std
被认为是不好的做法;但是,它是为分配要求的一部分,所以我把它在
你甚至都不需要一个数组。 – immibis 2015-02-10 21:02:05