2015-02-10 45 views
1

我为我的介绍性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

你甚至都不需要一个数组。 – immibis 2015-02-10 21:02:05

回答

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; 
} 

好像你走在这个Stack Overflow post提到如下Google Code University's C++ tutorial类。查看这些资源以更好地改进您的代码。

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; 

}