我为我的介绍性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
被认为是不好的做法;但是,这是作业要求的一部分,所以我把它留在了。
答案 0 :(得分:0)
您的评论已经在正确的轨道上了:
我觉得可能有一种方法可以通过数组和do ... while循环来实现这一点
您可以使用循环输入来完成此操作。这意味着您一直要求输入,直到他们为您提供有效的输入。
为此,我在用户输入周围放置一个循环,然后添加一些在开始输入后清理的代码。这意味着在它要求输入之前,它首先清除所有内容,并且每次循环时都执行相同的操作。
可能的解决方案是:
#include <iostream>
using namespace std;
float first;
float second;
float third;
float fourth;
float fifth;
float total;
int main(){
do {
// Clear and discard input errors
cin.clear();
cin.ignore(10000, '\n');
// Prompt the user to enter 5 decimal values
cout << "Enter 5 decimal values: ";
cin >> first >> second >> third >> fourth >> fifth;
} while (cin.fail());
// 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;
}
您所参加的课程似乎遵循此Google Code University's C++ tutorial中提到的Stack Overflow post。查看这些资源,以便对代码进行更多改进。
答案 1 :(得分:0)
使用while循环,您甚至不需要使用五个这样的变量:
#include <iostream>
#include <iomanip>
using namespace std;
float input;
float total;
int main(){
// Promt the user to enter 5 decimal values
int valuesEntered = 0;
while (valuesEntered < 5)
{
cout << "please enter " << (5 - (valuesEntered)) << " numbers: ";
cin >> input;
if (cin.fail()) {
cout << "Invalid entry; Please enter numbers only." << endl;
cin.clear();
cin.ignore(10000, '\n');
}
else
{
total += input;
valuesEntered++;
}
}
cout << fixed << setprecision(0) << "The total is: " << total << endl;
system("pause");
return 0;
}