【发布时间】:2015-02-10 21:01:28
【问题描述】:
我为我的 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 被认为是不好的做法;但是,这是作业要求的一部分,所以我把它留在了。
【问题讨论】:
-
你甚至不需要数组。
标签: c++ validation input refactoring